From 7f566bee45417d6679f216b4729488b8a7b458b7 Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Wed, 24 Aug 2022 19:06:15 +0200 Subject: [PATCH 1/7] Add preview, submit tx and tx stream APIs in Rust --- .../com/radixdlt/sbor/StateManagerSbor.java | 10 - .../statecomputer/RustStateComputer.java | 16 - .../statecomputer/preview/FeeSummary.java | 103 - .../statecomputer/preview/PreviewError.java | 80 - .../statecomputer/preview/PreviewFlags.java | 80 - .../statecomputer/preview/PreviewRequest.java | 140 -- .../statecomputer/preview/PreviewResult.java | 106 - .../radixdlt/statecomputer/PreviewTest.java | 139 -- state-manager/Cargo.lock | 1 + state-manager/core-api-server/Cargo.toml | 1 + .../core-api-server/core-api-spec.yaml | 258 +- .../src/core_api/generated/mod.rs | 58 +- .../src/core_api/generated/models.rs | 2120 ++++++++++++----- .../src/core_api/generated/server.rs | 146 +- .../core-api-server/src/core_api/mod.rs | 4 + .../src/core_api/network_configuration.rs | 48 + .../core-api-server/src/core_api/preview.rs | 177 ++ .../core-api-server/src/core_api/server.rs | 57 +- .../src/core_api/transactions.rs | 174 ++ .../src/jni/state_computer/dto.rs | 160 -- .../src/jni/state_computer/mod.rs | 35 +- state-manager/state-manager/src/lib.rs | 3 + .../state-manager/src/state_manager.rs | 33 +- .../src/store/in_memory_transaction_store.rs | 11 +- state-manager/state-manager/src/store/mod.rs | 2 +- state-manager/state-manager/src/types.rs | 15 +- 26 files changed, 2338 insertions(+), 1639 deletions(-) delete mode 100644 state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/FeeSummary.java delete mode 100644 state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewError.java delete mode 100644 state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewFlags.java delete mode 100644 state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewRequest.java delete mode 100644 state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewResult.java delete mode 100644 state-manager-bridge/src/test/java/com/radixdlt/statecomputer/PreviewTest.java create mode 100644 state-manager/core-api-server/src/core_api/network_configuration.rs create mode 100644 state-manager/core-api-server/src/core_api/preview.rs create mode 100644 state-manager/core-api-server/src/core_api/transactions.rs delete mode 100644 state-manager/state-manager/src/jni/state_computer/dto.rs diff --git a/state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java b/state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java index 7279e29a98..c42e8ecd66 100644 --- a/state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java +++ b/state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java @@ -78,11 +78,6 @@ import com.radixdlt.sbor.codec.CodecMap; import com.radixdlt.sbor.codec.StructCodec; import com.radixdlt.statecomputer.commit.CommitRequest; -import com.radixdlt.statecomputer.preview.FeeSummary; -import com.radixdlt.statecomputer.preview.PreviewError; -import com.radixdlt.statecomputer.preview.PreviewFlags; -import com.radixdlt.statecomputer.preview.PreviewRequest; -import com.radixdlt.statecomputer.preview.PreviewResult; import com.radixdlt.statemanager.CoreApiServerConfig; import com.radixdlt.statemanager.StateManagerConfig; import com.radixdlt.transaction.ExecutedTransactionReceipt; @@ -123,17 +118,12 @@ public static void registerCodecsWithCodecMap(CodecMap codecMap) { RustMempoolConfig.registerCodec(codecMap); StateManagerConfig.registerCodec(codecMap); RawTransaction.registerCodec(codecMap); - PreviewFlags.registerCodec(codecMap); - PreviewRequest.registerCodec(codecMap); - PreviewResult.registerCodec(codecMap); - PreviewError.registerCodec(codecMap); TransactionStatus.registerCodec(codecMap); Decimal.registerCodec(codecMap); LogLevel.registerCodec(codecMap); ComponentAddress.registerCodec(codecMap); PackageAddress.registerCodec(codecMap); ResourceAddress.registerCodec(codecMap); - FeeSummary.registerCodec(codecMap); TID.registerCodec(codecMap); StateManagerRuntimeError.registerCodec(codecMap); MempoolError.registerCodec(codecMap); diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java index 68e914c5a1..cf6cbf72f4 100644 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java +++ b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java @@ -65,16 +65,12 @@ package com.radixdlt.statecomputer; import com.google.common.reflect.TypeToken; -import com.radixdlt.lang.Result; import com.radixdlt.lang.Unit; import com.radixdlt.mempool.*; import com.radixdlt.rev2.ComponentAddress; import com.radixdlt.rev2.Decimal; import com.radixdlt.sbor.NativeCalls; import com.radixdlt.statecomputer.commit.CommitRequest; -import com.radixdlt.statecomputer.preview.PreviewError; -import com.radixdlt.statecomputer.preview.PreviewRequest; -import com.radixdlt.statecomputer.preview.PreviewResult; import com.radixdlt.statemanager.StateManager; import com.radixdlt.transaction.REv2TransactionAndProofStore; import com.radixdlt.transactions.RawTransaction; @@ -90,9 +86,6 @@ public RustStateComputer(StateManager stateManager) { verifyFunc = NativeCalls.Func1.with( stateManager, new TypeToken<>() {}, new TypeToken<>() {}, RustStateComputer::verify); - previewFunc = - NativeCalls.Func1.with( - stateManager, new TypeToken<>() {}, new TypeToken<>() {}, RustStateComputer::preview); commitFunc = NativeCalls.Func1.with( stateManager, new TypeToken<>() {}, new TypeToken<>() {}, RustStateComputer::commit); @@ -133,19 +126,10 @@ public boolean verify(RawTransaction transaction) { return verifyFunc.call(transaction); } - public Result preview(PreviewRequest previewRequest) { - return previewFunc.call(previewRequest); - } - private final NativeCalls.Func1 verifyFunc; private static native byte[] verify(StateManager stateManager, byte[] payload); - private final NativeCalls.Func1> - previewFunc; - - private static native byte[] preview(StateManager stateManager, byte[] payload); - private final NativeCalls.Func1 commitFunc; private static native byte[] commit(StateManager stateManager, byte[] payload); diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/FeeSummary.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/FeeSummary.java deleted file mode 100644 index 1f7c41fa93..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/FeeSummary.java +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.radixdlt.rev2.Decimal; -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; -import com.radixdlt.utils.UInt32; - -public record FeeSummary( - boolean loanFullyRepaid, - UInt32 costUnitLimit, - UInt32 costUnitsConsumed, - Decimal costUnitPrice, - UInt32 tipPercentage, - Decimal burned, - Decimal tipped) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - FeeSummary.class, - codecs -> - StructCodec.with( - FeeSummary::new, - codecs.of(boolean.class), - codecs.of(UInt32.class), - codecs.of(UInt32.class), - codecs.of(Decimal.class), - codecs.of(UInt32.class), - codecs.of(Decimal.class), - codecs.of(Decimal.class), - (t, encoder) -> - encoder.encode( - t.loanFullyRepaid, - t.costUnitLimit, - t.costUnitsConsumed, - t.costUnitPrice, - t.tipPercentage, - t.burned, - t.tipped))); - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewError.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewError.java deleted file mode 100644 index 28134503a4..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewError.java +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; - -public record PreviewError(String message) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewError.class, - codecs -> - StructCodec.with( - PreviewError::new, - codecs.of(String.class), - (t, encoder) -> encoder.encode(t.message))); - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewFlags.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewFlags.java deleted file mode 100644 index 055b676f98..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewFlags.java +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; - -public record PreviewFlags(boolean unlimitedLoan) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewFlags.class, - codecs -> - StructCodec.with( - PreviewFlags::new, - codecs.of(boolean.class), - (t, encoder) -> encoder.encode(t.unlimitedLoan))); - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewRequest.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewRequest.java deleted file mode 100644 index 56ca6463d0..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewRequest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.google.common.reflect.TypeToken; -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; -import com.radixdlt.utils.UInt32; -import com.radixdlt.utils.UInt64; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -public record PreviewRequest( - byte[] manifest, - UInt32 costUnitLimit, - UInt32 tipPercentage, - UInt64 nonce, - List signerPublicKeys, - PreviewFlags flags) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewRequest.class, - codecs -> - StructCodec.with( - PreviewRequest::new, - codecs.of(byte[].class), - codecs.of(UInt32.class), - codecs.of(UInt32.class), - codecs.of(UInt64.class), - codecs.of(new TypeToken>() {}), - codecs.of(PreviewFlags.class), - (t, encoder) -> - encoder.encode( - t.manifest, - t.costUnitLimit, - t.tipPercentage, - t.nonce, - t.signerPublicKeys, - t.flags))); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof PreviewRequest other) { - return Arrays.equals(other.manifest, manifest) - && Objects.equals(other.nonce, nonce) - && Objects.equals(other.costUnitLimit, costUnitLimit) - && Objects.equals(other.tipPercentage, tipPercentage) - && Objects.equals(other.signerPublicKeys, signerPublicKeys) - && Objects.equals(other.flags, flags); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash( - Arrays.hashCode(manifest), nonce, costUnitLimit, tipPercentage, signerPublicKeys, flags); - } - - @Override - public String toString() { - return "PreviewRequest{" - + "costUnitLimit=" - + costUnitLimit - + ", tipPercentage=" - + tipPercentage - + ", nonce=" - + nonce - + ", flags=" - + flags - + '}'; - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewResult.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewResult.java deleted file mode 100644 index 6d4f587af0..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewResult.java +++ /dev/null @@ -1,106 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.google.common.reflect.TypeToken; -import com.radixdlt.lang.Tuple; -import com.radixdlt.rev2.ComponentAddress; -import com.radixdlt.rev2.LogLevel; -import com.radixdlt.rev2.PackageAddress; -import com.radixdlt.rev2.ResourceAddress; -import com.radixdlt.rev2.TransactionStatus; -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; -import java.util.List; - -public record PreviewResult( - TransactionStatus transactionStatus, - FeeSummary transactionFee, - List> logs, - List newPackageAddresses, - List newComponentAddresses, - List newResourceAddresses) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewResult.class, - codecs -> - StructCodec.with( - PreviewResult::new, - codecs.of(TransactionStatus.class), - codecs.of(FeeSummary.class), - codecs.of(new TypeToken>>() {}), - codecs.of(new TypeToken>() {}), - codecs.of(new TypeToken>() {}), - codecs.of(new TypeToken>() {}), - (t, encoder) -> - encoder.encode( - t.transactionStatus, - t.transactionFee, - t.logs, - t.newPackageAddresses, - t.newComponentAddresses, - t.newResourceAddresses))); - } -} diff --git a/state-manager-bridge/src/test/java/com/radixdlt/statecomputer/PreviewTest.java b/state-manager-bridge/src/test/java/com/radixdlt/statecomputer/PreviewTest.java deleted file mode 100644 index 9a12a79475..0000000000 --- a/state-manager-bridge/src/test/java/com/radixdlt/statecomputer/PreviewTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.radixdlt.crypto.ECKeyPair; -import com.radixdlt.lang.Option; -import com.radixdlt.manifest.ManifestCompiler; -import com.radixdlt.rev2.TransactionStatus; -import com.radixdlt.statecomputer.preview.PreviewFlags; -import com.radixdlt.statecomputer.preview.PreviewRequest; -import com.radixdlt.statemanager.StateManager; -import com.radixdlt.statemanager.StateManagerConfig; -import com.radixdlt.utils.UInt32; -import com.radixdlt.utils.UInt64; -import java.util.List; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -public final class PreviewTest { - @Test - public void test_successful_preview() { - // Arrange - try (final var stateManager = - StateManager.createAndInitialize(new StateManagerConfig(Option.none()))) { - final var stateComputer = new RustStateComputer(stateManager); - final var manifest = ManifestCompiler.compile("CLEAR_AUTH_ZONE;", "LocalSimulator").unwrap(); - final var somePublicKey = ECKeyPair.generateNew().getPublicKey().getCompressedBytes(); - final var previewRequest = - new PreviewRequest( - manifest, - UInt32.fromNonNegativeInt(10000000), - UInt32.fromNonNegativeInt(0), - UInt64.fromNonNegativeLong(0L), - List.of(somePublicKey), - new PreviewFlags(true)); - - // Act - final var result = stateComputer.preview(previewRequest); - final var costUnitsConsumed = result.unwrap().transactionFee().costUnitsConsumed(); - - // Assert - assertTrue(result.unwrap().transactionStatus() instanceof TransactionStatus.Succeeded); - // Just to make sure we're getting some reasonable values back - assertTrue(costUnitsConsumed.gt(UInt32.fromNonNegativeInt(1000))); - assertTrue(costUnitsConsumed.lte(UInt32.fromNonNegativeInt(1000000))); - } - } - - @Test - public void test_decode_error_result() { - // Arrange - try (final var stateManager = - StateManager.createAndInitialize(new StateManagerConfig(Option.none()))) { - final var stateComputer = new RustStateComputer(stateManager); - final var manifest = Hex.decode("00"); // invalid manifest - final var somePublicKey = ECKeyPair.generateNew().getPublicKey().getCompressedBytes(); - final var previewRequest = - new PreviewRequest( - manifest, - UInt32.fromNonNegativeInt(100000000), - UInt32.fromNonNegativeInt(0), - UInt64.fromNonNegativeLong(0L), - List.of(somePublicKey), - new PreviewFlags(true)); - - // Act - final var result = stateComputer.preview(previewRequest); - - // Assert - assertTrue(result.isError()); - assertFalse(result.unwrapError().message().isBlank()); - } - } -} diff --git a/state-manager/Cargo.lock b/state-manager/Cargo.lock index e2288490b0..85b9f7415e 100644 --- a/state-manager/Cargo.lock +++ b/state-manager/Cargo.lock @@ -276,6 +276,7 @@ dependencies = [ "async-trait", "chrono", "futures", + "hex", "hyper", "jni", "lazy_static", diff --git a/state-manager/core-api-server/Cargo.toml b/state-manager/core-api-server/Cargo.toml index c775eeb16b..60836a640c 100644 --- a/state-manager/core-api-server/Cargo.toml +++ b/state-manager/core-api-server/Cargo.toml @@ -42,3 +42,4 @@ serde_ignored = "0.1.1" url = "2.1" lazy_static = "1.4" regex = "1.3" +hex = { version = "0.4.3", default-features = false } diff --git a/state-manager/core-api-server/core-api-spec.yaml b/state-manager/core-api-server/core-api-spec.yaml index 5e589451bb..af9fc8bed8 100644 --- a/state-manager/core-api-server/core-api-spec.yaml +++ b/state-manager/core-api-server/core-api-spec.yaml @@ -41,7 +41,7 @@ paths: schema: "$ref": "#/components/schemas/NetworkConfigurationResponse" '500': - description: An error occurred + description: Server error content: application/json: schema: @@ -65,8 +65,14 @@ paths: application/json: schema: "$ref": "#/components/schemas/TransactionSubmitResponse" + '400': + description: Client error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" '500': - description: An error occurred + description: Server error content: application/json: schema: @@ -90,8 +96,44 @@ paths: application/json: schema: "$ref": "#/components/schemas/TransactionPreviewResponse" + '400': + description: Client error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + '500': + description: Server error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + "/transactions": + post: + summary: Get committed transactions + tags: + - Transaction + requestBody: + required: true + content: + application/json: + schema: + "$ref": "#/components/schemas/CommittedTransactionsRequest" + responses: + '200': + description: Committed transactions response + content: + application/json: + schema: + "$ref": "#/components/schemas/CommittedTransactionsResponse" + '400': + description: Client error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" '500': - description: An error occurred + description: Server error content: application/json: schema: @@ -101,6 +143,121 @@ components: ########################### # GENERAL / SHARED MODELS # ########################### + TransactionStatus: + type: string + enum: + - succeeded + - failed + - rejected + description: The status of the transaction + TransactionReceipt: + type: object + required: + - status + - fee_summary + properties: + status: + "$ref": "#/components/schemas/TransactionStatus" + fee_summary: + "$ref": "#/components/schemas/FeeSummary" + output: + type: array + items: + type: string + error_message: + type: string + NotarizedTransaction: + type: object + required: + - hash + - signed_intent + - notary_signature + properties: + hash: + type: string + signed_intent: + "$ref": "#/components/schemas/SignedTransactionIntent" + notary_signature: + type: string + SignedTransactionIntent: + type: object + required: + - hash + - intent + - intent_signatures + properties: + hash: + type: string + intent: + "$ref": "#/components/schemas/TransactionIntent" + intent_signatures: + type: array + items: + "$ref": "#/components/schemas/IntentSignature" + IntentSignature: + type: object + required: + - public_key + - signature + properties: + public_key: + type: string + signature: + type: string + TransactionIntent: + type: object + required: + - hash + - header + - manifest + properties: + hash: + type: string + header: + "$ref": "#/components/schemas/TransactionHeader" + manifest: + type: string + TransactionHeader: + type: object + required: + - version + - network + - start_epoch_inclusive + - end_epoch_exclusive + - nonce + - notary_public_key + - notary_as_signatory + - cost_unit_limit + - tip_percentage + properties: + version: + type: integer + network: + "$ref": "#/components/schemas/Network" + start_epoch_inclusive: + type: string + end_epoch_exclusive: + type: string + nonce: + type: string + notary_public_key: + type: string + notary_as_signatory: + type: boolean + cost_unit_limit: + type: string + tip_percentage: + type: string + Network: + type: object + required: + - id + - name + properties: + id: + type: string + name: + type: string NetworkIdentifier: type: object required: @@ -212,49 +369,12 @@ components: ######################################### # GENERAL / SHARED MODELS - Transaction # ######################################### - TransactionStatus: - type: object - required: - - type - properties: - type: - type: string - discriminator: - propertyName: type - mapping: - TransactionStatusRejected: "#/components/schemas/TransactionStatusRejected" - TransactionStatusSucceeded: "#/components/schemas/TransactionStatusSucceeded" - TransactionStatusFailed: "#/components/schemas/TransactionStatusFailed" - TransactionStatusRejected: - allOf: - - $ref: "#/components/schemas/TransactionStatus" - - type: object - TransactionStatusSucceeded: - allOf: - - $ref: "#/components/schemas/TransactionStatus" - - type: object - required: - - output - properties: - output: - type: array - items: - type: string - TransactionStatusFailed: - allOf: - - $ref: "#/components/schemas/TransactionStatus" - - type: object - required: - - message - properties: - message: - type: string FeeSummary: type: object required: - loan_fully_repaid - cost_unit_limit - - cost_units_consumed + - cost_unit_consumed - cost_unit_price - tip_percentage - xrd_burned @@ -264,7 +384,7 @@ components: type: boolean cost_unit_limit: type: string - cost_units_consumed: + cost_unit_consumed: type: string cost_unit_price: type: string @@ -397,7 +517,6 @@ components: properties: transaction_status: "$ref": "#/components/schemas/TransactionStatus" - description: The status of the transaction transaction_fee: "$ref": "#/components/schemas/FeeSummary" description: Fees to be paid @@ -427,4 +546,55 @@ components: description: A list of new resource addresses type: array items: - type: string \ No newline at end of file + type: string + output: + type: array + items: + type: string + error_message: + type: string +########################## +# REQUEST: /transactions # +########################## + CommittedTransactionsRequest: + description: A request to retrieve a sublist of committed transactions from the + ledger. + type: object + required: + - network_identifier + - state_version + - limit + properties: + network_identifier: + "$ref": "#/components/schemas/NetworkIdentifier" + description: The name of the network + state_version: + type: integer + format: int64 + limit: + description: The maximum number of transactions that will be returned. + type: integer + CommittedTransactionsResponse: + type: object + required: + - state_version + - transactions + properties: + state_version: + type: integer + format: int64 + transactions: + description: A committed transactions list starting from the `state_version`. + type: array + items: + "$ref": "#/components/schemas/CommittedTransaction" + CommittedTransaction: + type: object + required: + - notarized_transaction + - receipt + properties: + notarized_transaction: + "$ref": "#/components/schemas/NotarizedTransaction" + receipt: + "$ref": "#/components/schemas/TransactionReceipt" diff --git a/state-manager/core-api-server/src/core_api/generated/mod.rs b/state-manager/core-api-server/src/core_api/generated/mod.rs index 2b04ea075c..e9bd0d8963 100644 --- a/state-manager/core-api-server/src/core_api/generated/mod.rs +++ b/state-manager/core-api-server/src/core_api/generated/mod.rs @@ -19,8 +19,8 @@ pub enum StatusNetworkConfigurationPostResponse { NetworkConfiguration (models::NetworkConfigurationResponse) , - /// An error occurred - AnErrorOccurred + /// Server error + ServerError (models::ErrorResponse) } @@ -31,8 +31,12 @@ pub enum TransactionPreviewPostResponse { TransactionPreviewResponse (models::TransactionPreviewResponse) , - /// An error occurred - AnErrorOccurred + /// Client error + ClientError + (models::ErrorResponse) + , + /// Server error + ServerError (models::ErrorResponse) } @@ -43,8 +47,28 @@ pub enum TransactionSubmitPostResponse { TransactionSubmitResponse (models::TransactionSubmitResponse) , - /// An error occurred - AnErrorOccurred + /// Client error + ClientError + (models::ErrorResponse) + , + /// Server error + ServerError + (models::ErrorResponse) +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +pub enum TransactionsPostResponse { + /// Committed transactions response + CommittedTransactionsResponse + (models::CommittedTransactionsResponse) + , + /// Client error + ClientError + (models::ErrorResponse) + , + /// Server error + ServerError (models::ErrorResponse) } @@ -72,6 +96,12 @@ pub trait Api { transaction_submit_request: models::TransactionSubmitRequest, context: &C) -> Result; + /// Get committed transactions + async fn transactions_post( + &self, + committed_transactions_request: models::CommittedTransactionsRequest, + context: &C) -> Result; + } /// API where `Context` isn't passed on every API call @@ -99,6 +129,12 @@ pub trait ApiNoContext { transaction_submit_request: models::TransactionSubmitRequest, ) -> Result; + /// Get committed transactions + async fn transactions_post( + &self, + committed_transactions_request: models::CommittedTransactionsRequest, + ) -> Result; + } /// Trait to extend an API to make it easy to bind it to a context. @@ -153,6 +189,16 @@ impl + Send + Sync, C: Clone + Send + Sync> ApiNoContext for Contex self.api().transaction_submit_post(transaction_submit_request, &context).await } + /// Get committed transactions + async fn transactions_post( + &self, + committed_transactions_request: models::CommittedTransactionsRequest, + ) -> Result + { + let context = self.context().clone(); + self.api().transactions_post(committed_transactions_request, &context).await + } + } diff --git a/state-manager/core-api-server/src/core_api/generated/models.rs b/state-manager/core-api-server/src/core_api/generated/models.rs index ed0c554d66..06034f8961 100644 --- a/state-manager/core-api-server/src/core_api/generated/models.rs +++ b/state-manager/core-api-server/src/core_api/generated/models.rs @@ -151,45 +151,50 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct CoreErrorDetails { - #[serde(rename = "type")] - pub type_: String, +pub struct CommittedTransaction { + #[serde(rename = "notarized_transaction")] + pub notarized_transaction: models::NotarizedTransaction, + + #[serde(rename = "receipt")] + pub receipt: models::TransactionReceipt, } -impl CoreErrorDetails { - pub fn new(type_: String, ) -> CoreErrorDetails { - CoreErrorDetails { - type_: type_, +impl CommittedTransaction { + pub fn new(notarized_transaction: models::NotarizedTransaction, receipt: models::TransactionReceipt, ) -> CommittedTransaction { + CommittedTransaction { + notarized_transaction: notarized_transaction, + receipt: receipt, } } } -/// Converts the CoreErrorDetails value to the Query Parameters representation (style=form, explode=false) +/// Converts the CommittedTransaction value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for CoreErrorDetails { +impl std::string::ToString for CommittedTransaction { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping notarized_transaction in query parameter serialization - params.push("type".to_string()); - params.push(self.type_.to_string()); + // Skipping receipt in query parameter serialization params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a CoreErrorDetails value +/// Converts Query Parameters representation (style=form, explode=false) to a CommittedTransaction value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for CoreErrorDetails { +impl std::str::FromStr for CommittedTransaction { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, + pub notarized_transaction: Vec, + pub receipt: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -201,13 +206,14 @@ impl std::str::FromStr for CoreErrorDetails { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing CoreErrorDetails".to_string()) + None => return std::result::Result::Err("Missing value while parsing CommittedTransaction".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing CoreErrorDetails".to_string()) + "notarized_transaction" => intermediate_rep.notarized_transaction.push(::from_str(val).map_err(|x| format!("{}", x))?), + "receipt" => intermediate_rep.receipt.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransaction".to_string()) } } @@ -216,40 +222,41 @@ impl std::str::FromStr for CoreErrorDetails { } // Use the intermediate representation to return the struct - std::result::Result::Ok(CoreErrorDetails { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in CoreErrorDetails".to_string())?, + std::result::Result::Ok(CommittedTransaction { + notarized_transaction: intermediate_rep.notarized_transaction.into_iter().next().ok_or("notarized_transaction missing in CommittedTransaction".to_string())?, + receipt: intermediate_rep.receipt.into_iter().next().ok_or("receipt missing in CommittedTransaction".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for CoreErrorDetails - value: {} is invalid {}", + format!("Invalid header value for CommittedTransaction - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into CoreErrorDetails - {}", + format!("Unable to convert header value '{}' into CommittedTransaction - {}", value, err)) } }, @@ -261,79 +268,65 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// A request to retrieve a sublist of committed transactions from the ledger. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct ErrorResponse { - /// A numeric code corresponding to the given error type, roughly aligned with HTTP Status Code semantics (eg 400/404/500). - #[serde(rename = "code")] - pub code: isize, - - /// A human-readable error message. - #[serde(rename = "message")] - pub message: String, +pub struct CommittedTransactionsRequest { + #[serde(rename = "network_identifier")] + pub network_identifier: models::NetworkIdentifier, - #[serde(rename = "details")] - #[serde(skip_serializing_if="Option::is_none")] - pub details: Option, + #[serde(rename = "state_version")] + pub state_version: i64, - /// A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. - #[serde(rename = "trace_id")] - #[serde(skip_serializing_if="Option::is_none")] - pub trace_id: Option, + /// The maximum number of transactions that will be returned. + #[serde(rename = "limit")] + pub limit: isize, } -impl ErrorResponse { - pub fn new(code: isize, message: String, ) -> ErrorResponse { - ErrorResponse { - code: code, - message: message, - details: None, - trace_id: None, +impl CommittedTransactionsRequest { + pub fn new(network_identifier: models::NetworkIdentifier, state_version: i64, limit: isize, ) -> CommittedTransactionsRequest { + CommittedTransactionsRequest { + network_identifier: network_identifier, + state_version: state_version, + limit: limit, } } } -/// Converts the ErrorResponse value to the Query Parameters representation (style=form, explode=false) +/// Converts the CommittedTransactionsRequest value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for ErrorResponse { +impl std::string::ToString for CommittedTransactionsRequest { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping network_identifier in query parameter serialization - params.push("code".to_string()); - params.push(self.code.to_string()); - - - params.push("message".to_string()); - params.push(self.message.to_string()); - // Skipping details in query parameter serialization + params.push("state_version".to_string()); + params.push(self.state_version.to_string()); - if let Some(ref trace_id) = self.trace_id { - params.push("trace_id".to_string()); - params.push(trace_id.to_string()); - } + params.push("limit".to_string()); + params.push(self.limit.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a ErrorResponse value +/// Converts Query Parameters representation (style=form, explode=false) to a CommittedTransactionsRequest value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for ErrorResponse { +impl std::str::FromStr for CommittedTransactionsRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub code: Vec, - pub message: Vec, - pub details: Vec, - pub trace_id: Vec, + pub network_identifier: Vec, + pub state_version: Vec, + pub limit: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -345,16 +338,15 @@ impl std::str::FromStr for ErrorResponse { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing ErrorResponse".to_string()) + None => return std::result::Result::Err("Missing value while parsing CommittedTransactionsRequest".to_string()) }; if let Some(key) = key_result { match key { - "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - "details" => intermediate_rep.details.push(::from_str(val).map_err(|x| format!("{}", x))?), - "trace_id" => intermediate_rep.trace_id.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing ErrorResponse".to_string()) + "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), + "state_version" => intermediate_rep.state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "limit" => intermediate_rep.limit.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransactionsRequest".to_string()) } } @@ -363,43 +355,42 @@ impl std::str::FromStr for ErrorResponse { } // Use the intermediate representation to return the struct - std::result::Result::Ok(ErrorResponse { - code: intermediate_rep.code.into_iter().next().ok_or("code missing in ErrorResponse".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in ErrorResponse".to_string())?, - details: intermediate_rep.details.into_iter().next(), - trace_id: intermediate_rep.trace_id.into_iter().next(), + std::result::Result::Ok(CommittedTransactionsRequest { + network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in CommittedTransactionsRequest".to_string())?, + state_version: intermediate_rep.state_version.into_iter().next().ok_or("state_version missing in CommittedTransactionsRequest".to_string())?, + limit: intermediate_rep.limit.into_iter().next().ok_or("limit missing in CommittedTransactionsRequest".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for ErrorResponse - value: {} is invalid {}", + format!("Invalid header value for CommittedTransactionsRequest - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into ErrorResponse - {}", + format!("Unable to convert header value '{}' into CommittedTransactionsRequest - {}", value, err)) } }, @@ -413,99 +404,53 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FeeSummary { - #[serde(rename = "loan_fully_repaid")] - pub loan_fully_repaid: bool, - - #[serde(rename = "cost_unit_limit")] - pub cost_unit_limit: String, - - #[serde(rename = "cost_units_consumed")] - pub cost_units_consumed: String, - - #[serde(rename = "cost_unit_price")] - pub cost_unit_price: String, +pub struct CommittedTransactionsResponse { + #[serde(rename = "state_version")] + pub state_version: i64, - #[serde(rename = "tip_percentage")] - pub tip_percentage: String, - - #[serde(rename = "xrd_burned")] - pub xrd_burned: String, - - #[serde(rename = "xrd_tipped")] - pub xrd_tipped: String, + /// A committed transactions list starting from the `state_version`. + #[serde(rename = "transactions")] + pub transactions: Vec, } -impl FeeSummary { - pub fn new(loan_fully_repaid: bool, cost_unit_limit: String, cost_units_consumed: String, cost_unit_price: String, tip_percentage: String, xrd_burned: String, xrd_tipped: String, ) -> FeeSummary { - FeeSummary { - loan_fully_repaid: loan_fully_repaid, - cost_unit_limit: cost_unit_limit, - cost_units_consumed: cost_units_consumed, - cost_unit_price: cost_unit_price, - tip_percentage: tip_percentage, - xrd_burned: xrd_burned, - xrd_tipped: xrd_tipped, +impl CommittedTransactionsResponse { + pub fn new(state_version: i64, transactions: Vec, ) -> CommittedTransactionsResponse { + CommittedTransactionsResponse { + state_version: state_version, + transactions: transactions, } } } -/// Converts the FeeSummary value to the Query Parameters representation (style=form, explode=false) +/// Converts the CommittedTransactionsResponse value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for FeeSummary { +impl std::string::ToString for CommittedTransactionsResponse { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("loan_fully_repaid".to_string()); - params.push(self.loan_fully_repaid.to_string()); - - - params.push("cost_unit_limit".to_string()); - params.push(self.cost_unit_limit.to_string()); - - - params.push("cost_units_consumed".to_string()); - params.push(self.cost_units_consumed.to_string()); - - - params.push("cost_unit_price".to_string()); - params.push(self.cost_unit_price.to_string()); - - - params.push("tip_percentage".to_string()); - params.push(self.tip_percentage.to_string()); - - - params.push("xrd_burned".to_string()); - params.push(self.xrd_burned.to_string()); + params.push("state_version".to_string()); + params.push(self.state_version.to_string()); - - params.push("xrd_tipped".to_string()); - params.push(self.xrd_tipped.to_string()); + // Skipping transactions in query parameter serialization params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a FeeSummary value +/// Converts Query Parameters representation (style=form, explode=false) to a CommittedTransactionsResponse value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for FeeSummary { +impl std::str::FromStr for CommittedTransactionsResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub loan_fully_repaid: Vec, - pub cost_unit_limit: Vec, - pub cost_units_consumed: Vec, - pub cost_unit_price: Vec, - pub tip_percentage: Vec, - pub xrd_burned: Vec, - pub xrd_tipped: Vec, + pub state_version: Vec, + pub transactions: Vec>, } let mut intermediate_rep = IntermediateRep::default(); @@ -517,19 +462,14 @@ impl std::str::FromStr for FeeSummary { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing FeeSummary".to_string()) + None => return std::result::Result::Err("Missing value while parsing CommittedTransactionsResponse".to_string()) }; if let Some(key) = key_result { match key { - "loan_fully_repaid" => intermediate_rep.loan_fully_repaid.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cost_units_consumed" => intermediate_rep.cost_units_consumed.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cost_unit_price" => intermediate_rep.cost_unit_price.push(::from_str(val).map_err(|x| format!("{}", x))?), - "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), - "xrd_burned" => intermediate_rep.xrd_burned.push(::from_str(val).map_err(|x| format!("{}", x))?), - "xrd_tipped" => intermediate_rep.xrd_tipped.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing FeeSummary".to_string()) + "state_version" => intermediate_rep.state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "transactions" => return std::result::Result::Err("Parsing a container in this style is not supported in CommittedTransactionsResponse".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransactionsResponse".to_string()) } } @@ -538,46 +478,41 @@ impl std::str::FromStr for FeeSummary { } // Use the intermediate representation to return the struct - std::result::Result::Ok(FeeSummary { - loan_fully_repaid: intermediate_rep.loan_fully_repaid.into_iter().next().ok_or("loan_fully_repaid missing in FeeSummary".to_string())?, - cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in FeeSummary".to_string())?, - cost_units_consumed: intermediate_rep.cost_units_consumed.into_iter().next().ok_or("cost_units_consumed missing in FeeSummary".to_string())?, - cost_unit_price: intermediate_rep.cost_unit_price.into_iter().next().ok_or("cost_unit_price missing in FeeSummary".to_string())?, - tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in FeeSummary".to_string())?, - xrd_burned: intermediate_rep.xrd_burned.into_iter().next().ok_or("xrd_burned missing in FeeSummary".to_string())?, - xrd_tipped: intermediate_rep.xrd_tipped.into_iter().next().ok_or("xrd_tipped missing in FeeSummary".to_string())?, + std::result::Result::Ok(CommittedTransactionsResponse { + state_version: intermediate_rep.state_version.into_iter().next().ok_or("state_version missing in CommittedTransactionsResponse".to_string())?, + transactions: intermediate_rep.transactions.into_iter().next().ok_or("transactions missing in CommittedTransactionsResponse".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for FeeSummary - value: {} is invalid {}", + format!("Invalid header value for CommittedTransactionsResponse - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into FeeSummary - {}", + format!("Unable to convert header value '{}' into CommittedTransactionsResponse - {}", value, err)) } }, @@ -591,60 +526,38 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InternalServerError { +pub struct CoreErrorDetails { #[serde(rename = "type")] pub type_: String, - #[serde(rename = "exception")] - #[serde(skip_serializing_if="Option::is_none")] - pub exception: Option, - - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, - } -impl InternalServerError { - pub fn new(type_: String, ) -> InternalServerError { - InternalServerError { +impl CoreErrorDetails { + pub fn new(type_: String, ) -> CoreErrorDetails { + CoreErrorDetails { type_: type_, - exception: None, - cause: None, } } } -/// Converts the InternalServerError value to the Query Parameters representation (style=form, explode=false) +/// Converts the CoreErrorDetails value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InternalServerError { +impl std::string::ToString for CoreErrorDetails { fn to_string(&self) -> String { let mut params: Vec = vec![]; params.push("type".to_string()); params.push(self.type_.to_string()); - - if let Some(ref exception) = self.exception { - params.push("exception".to_string()); - params.push(exception.to_string()); - } - - - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } - params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InternalServerError value +/// Converts Query Parameters representation (style=form, explode=false) to a CoreErrorDetails value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InternalServerError { +impl std::str::FromStr for CoreErrorDetails { type Err = String; fn from_str(s: &str) -> std::result::Result { @@ -652,8 +565,6 @@ impl std::str::FromStr for InternalServerError { // An intermediate representation of the struct to use for parsing. struct IntermediateRep { pub type_: Vec, - pub exception: Vec, - pub cause: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -665,15 +576,13 @@ impl std::str::FromStr for InternalServerError { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InternalServerError".to_string()) + None => return std::result::Result::Err("Missing value while parsing CoreErrorDetails".to_string()) }; if let Some(key) = key_result { match key { "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "exception" => intermediate_rep.exception.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InternalServerError".to_string()) + _ => return std::result::Result::Err("Unexpected key while parsing CoreErrorDetails".to_string()) } } @@ -682,42 +591,40 @@ impl std::str::FromStr for InternalServerError { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InternalServerError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InternalServerError".to_string())?, - exception: intermediate_rep.exception.into_iter().next(), - cause: intermediate_rep.cause.into_iter().next(), + std::result::Result::Ok(CoreErrorDetails { + type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in CoreErrorDetails".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InternalServerError - value: {} is invalid {}", + format!("Invalid header value for CoreErrorDetails - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InternalServerError - {}", + format!("Unable to convert header value '{}' into CoreErrorDetails - {}", value, err)) } }, @@ -731,16 +638,607 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InternalServerErrorAllOf { - #[serde(rename = "exception")] - #[serde(skip_serializing_if="Option::is_none")] - pub exception: Option, +pub struct ErrorResponse { + /// A numeric code corresponding to the given error type, roughly aligned with HTTP Status Code semantics (eg 400/404/500). + #[serde(rename = "code")] + pub code: isize, - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, + /// A human-readable error message. + #[serde(rename = "message")] + pub message: String, -} + #[serde(rename = "details")] + #[serde(skip_serializing_if="Option::is_none")] + pub details: Option, + + /// A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. + #[serde(rename = "trace_id")] + #[serde(skip_serializing_if="Option::is_none")] + pub trace_id: Option, + +} + +impl ErrorResponse { + pub fn new(code: isize, message: String, ) -> ErrorResponse { + ErrorResponse { + code: code, + message: message, + details: None, + trace_id: None, + } + } +} + +/// Converts the ErrorResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ErrorResponse { + fn to_string(&self) -> String { + let mut params: Vec = vec![]; + + params.push("code".to_string()); + params.push(self.code.to_string()); + + + params.push("message".to_string()); + params.push(self.message.to_string()); + + // Skipping details in query parameter serialization + + + if let Some(ref trace_id) = self.trace_id { + params.push("trace_id".to_string()); + params.push(trace_id.to_string()); + } + + params.join(",").to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ErrorResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ErrorResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + #[derive(Default)] + // An intermediate representation of the struct to use for parsing. + struct IntermediateRep { + pub code: Vec, + pub message: Vec, + pub details: Vec, + pub trace_id: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(',').into_iter(); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ErrorResponse".to_string()) + }; + + if let Some(key) = key_result { + match key { + "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| format!("{}", x))?), + "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), + "details" => intermediate_rep.details.push(::from_str(val).map_err(|x| format!("{}", x))?), + "trace_id" => intermediate_rep.trace_id.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing ErrorResponse".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ErrorResponse { + code: intermediate_rep.code.into_iter().next().ok_or("code missing in ErrorResponse".to_string())?, + message: intermediate_rep.message.into_iter().next().ok_or("message missing in ErrorResponse".to_string())?, + details: intermediate_rep.details.into_iter().next(), + trace_id: intermediate_rep.trace_id.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + + +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ErrorResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + + +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ErrorResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct FeeSummary { + #[serde(rename = "loan_fully_repaid")] + pub loan_fully_repaid: bool, + + #[serde(rename = "cost_unit_limit")] + pub cost_unit_limit: String, + + #[serde(rename = "cost_unit_consumed")] + pub cost_unit_consumed: String, + + #[serde(rename = "cost_unit_price")] + pub cost_unit_price: String, + + #[serde(rename = "tip_percentage")] + pub tip_percentage: String, + + #[serde(rename = "xrd_burned")] + pub xrd_burned: String, + + #[serde(rename = "xrd_tipped")] + pub xrd_tipped: String, + +} + +impl FeeSummary { + pub fn new(loan_fully_repaid: bool, cost_unit_limit: String, cost_unit_consumed: String, cost_unit_price: String, tip_percentage: String, xrd_burned: String, xrd_tipped: String, ) -> FeeSummary { + FeeSummary { + loan_fully_repaid: loan_fully_repaid, + cost_unit_limit: cost_unit_limit, + cost_unit_consumed: cost_unit_consumed, + cost_unit_price: cost_unit_price, + tip_percentage: tip_percentage, + xrd_burned: xrd_burned, + xrd_tipped: xrd_tipped, + } + } +} + +/// Converts the FeeSummary value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for FeeSummary { + fn to_string(&self) -> String { + let mut params: Vec = vec![]; + + params.push("loan_fully_repaid".to_string()); + params.push(self.loan_fully_repaid.to_string()); + + + params.push("cost_unit_limit".to_string()); + params.push(self.cost_unit_limit.to_string()); + + + params.push("cost_unit_consumed".to_string()); + params.push(self.cost_unit_consumed.to_string()); + + + params.push("cost_unit_price".to_string()); + params.push(self.cost_unit_price.to_string()); + + + params.push("tip_percentage".to_string()); + params.push(self.tip_percentage.to_string()); + + + params.push("xrd_burned".to_string()); + params.push(self.xrd_burned.to_string()); + + + params.push("xrd_tipped".to_string()); + params.push(self.xrd_tipped.to_string()); + + params.join(",").to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a FeeSummary value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for FeeSummary { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + #[derive(Default)] + // An intermediate representation of the struct to use for parsing. + struct IntermediateRep { + pub loan_fully_repaid: Vec, + pub cost_unit_limit: Vec, + pub cost_unit_consumed: Vec, + pub cost_unit_price: Vec, + pub tip_percentage: Vec, + pub xrd_burned: Vec, + pub xrd_tipped: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(',').into_iter(); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing FeeSummary".to_string()) + }; + + if let Some(key) = key_result { + match key { + "loan_fully_repaid" => intermediate_rep.loan_fully_repaid.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_consumed" => intermediate_rep.cost_unit_consumed.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_price" => intermediate_rep.cost_unit_price.push(::from_str(val).map_err(|x| format!("{}", x))?), + "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), + "xrd_burned" => intermediate_rep.xrd_burned.push(::from_str(val).map_err(|x| format!("{}", x))?), + "xrd_tipped" => intermediate_rep.xrd_tipped.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing FeeSummary".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(FeeSummary { + loan_fully_repaid: intermediate_rep.loan_fully_repaid.into_iter().next().ok_or("loan_fully_repaid missing in FeeSummary".to_string())?, + cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in FeeSummary".to_string())?, + cost_unit_consumed: intermediate_rep.cost_unit_consumed.into_iter().next().ok_or("cost_unit_consumed missing in FeeSummary".to_string())?, + cost_unit_price: intermediate_rep.cost_unit_price.into_iter().next().ok_or("cost_unit_price missing in FeeSummary".to_string())?, + tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in FeeSummary".to_string())?, + xrd_burned: intermediate_rep.xrd_burned.into_iter().next().ok_or("xrd_burned missing in FeeSummary".to_string())?, + xrd_tipped: intermediate_rep.xrd_tipped.into_iter().next().ok_or("xrd_tipped missing in FeeSummary".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + + +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for FeeSummary - value: {} is invalid {}", + hdr_value, e)) + } + } +} + + +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FeeSummary - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct IntentSignature { + #[serde(rename = "public_key")] + pub public_key: String, + + #[serde(rename = "signature")] + pub signature: String, + +} + +impl IntentSignature { + pub fn new(public_key: String, signature: String, ) -> IntentSignature { + IntentSignature { + public_key: public_key, + signature: signature, + } + } +} + +/// Converts the IntentSignature value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for IntentSignature { + fn to_string(&self) -> String { + let mut params: Vec = vec![]; + + params.push("public_key".to_string()); + params.push(self.public_key.to_string()); + + + params.push("signature".to_string()); + params.push(self.signature.to_string()); + + params.join(",").to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a IntentSignature value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for IntentSignature { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + #[derive(Default)] + // An intermediate representation of the struct to use for parsing. + struct IntermediateRep { + pub public_key: Vec, + pub signature: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(',').into_iter(); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing IntentSignature".to_string()) + }; + + if let Some(key) = key_result { + match key { + "public_key" => intermediate_rep.public_key.push(::from_str(val).map_err(|x| format!("{}", x))?), + "signature" => intermediate_rep.signature.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing IntentSignature".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(IntentSignature { + public_key: intermediate_rep.public_key.into_iter().next().ok_or("public_key missing in IntentSignature".to_string())?, + signature: intermediate_rep.signature.into_iter().next().ok_or("signature missing in IntentSignature".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + + +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for IntentSignature - value: {} is invalid {}", + hdr_value, e)) + } + } +} + + +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into IntentSignature - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct InternalServerError { + #[serde(rename = "type")] + pub type_: String, + + #[serde(rename = "exception")] + #[serde(skip_serializing_if="Option::is_none")] + pub exception: Option, + + #[serde(rename = "cause")] + #[serde(skip_serializing_if="Option::is_none")] + pub cause: Option, + +} + +impl InternalServerError { + pub fn new(type_: String, ) -> InternalServerError { + InternalServerError { + type_: type_, + exception: None, + cause: None, + } + } +} + +/// Converts the InternalServerError value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for InternalServerError { + fn to_string(&self) -> String { + let mut params: Vec = vec![]; + + params.push("type".to_string()); + params.push(self.type_.to_string()); + + + if let Some(ref exception) = self.exception { + params.push("exception".to_string()); + params.push(exception.to_string()); + } + + + if let Some(ref cause) = self.cause { + params.push("cause".to_string()); + params.push(cause.to_string()); + } + + params.join(",").to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a InternalServerError value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for InternalServerError { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + #[derive(Default)] + // An intermediate representation of the struct to use for parsing. + struct IntermediateRep { + pub type_: Vec, + pub exception: Vec, + pub cause: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(',').into_iter(); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing InternalServerError".to_string()) + }; + + if let Some(key) = key_result { + match key { + "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), + "exception" => intermediate_rep.exception.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing InternalServerError".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(InternalServerError { + type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InternalServerError".to_string())?, + exception: intermediate_rep.exception.into_iter().next(), + cause: intermediate_rep.cause.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + + +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for InternalServerError - value: {} is invalid {}", + hdr_value, e)) + } + } +} + + +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into InternalServerError - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct InternalServerErrorAllOf { + #[serde(rename = "exception")] + #[serde(skip_serializing_if="Option::is_none")] + pub exception: Option, + + #[serde(rename = "cause")] + #[serde(skip_serializing_if="Option::is_none")] + pub cause: Option, + +} impl InternalServerErrorAllOf { pub fn new() -> InternalServerErrorAllOf { @@ -1804,6 +2302,129 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Network { + #[serde(rename = "id")] + pub id: String, + + #[serde(rename = "name")] + pub name: String, + +} + +impl Network { + pub fn new(id: String, name: String, ) -> Network { + Network { + id: id, + name: name, + } + } +} + +/// Converts the Network value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Network { + fn to_string(&self) -> String { + let mut params: Vec = vec![]; + + params.push("id".to_string()); + params.push(self.id.to_string()); + + + params.push("name".to_string()); + params.push(self.name.to_string()); + + params.join(",").to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Network value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Network { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + #[derive(Default)] + // An intermediate representation of the struct to use for parsing. + struct IntermediateRep { + pub id: Vec, + pub name: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(',').into_iter(); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Network".to_string()) + }; + + if let Some(key) = key_result { + match key { + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| format!("{}", x))?), + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing Network".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Network { + id: intermediate_rep.id.into_iter().next().ok_or("id missing in Network".to_string())?, + name: intermediate_rep.name.into_iter().next().ok_or("name missing in Network".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + + +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Network - value: {} is invalid {}", + hdr_value, e)) + } + } +} + + +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Network - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct NetworkConfigurationResponse { @@ -2401,54 +3022,61 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct PreviewError { - #[serde(rename = "type")] - pub type_: String, +pub struct NotarizedTransaction { + #[serde(rename = "hash")] + pub hash: String, - #[serde(rename = "message")] - pub message: String, + #[serde(rename = "signed_intent")] + pub signed_intent: models::SignedTransactionIntent, + + #[serde(rename = "notary_signature")] + pub notary_signature: String, } -impl PreviewError { - pub fn new(type_: String, message: String, ) -> PreviewError { - PreviewError { - type_: type_, - message: message, +impl NotarizedTransaction { + pub fn new(hash: String, signed_intent: models::SignedTransactionIntent, notary_signature: String, ) -> NotarizedTransaction { + NotarizedTransaction { + hash: hash, + signed_intent: signed_intent, + notary_signature: notary_signature, } } } -/// Converts the PreviewError value to the Query Parameters representation (style=form, explode=false) +/// Converts the NotarizedTransaction value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for PreviewError { +impl std::string::ToString for NotarizedTransaction { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("hash".to_string()); + params.push(self.hash.to_string()); + // Skipping signed_intent in query parameter serialization - params.push("message".to_string()); - params.push(self.message.to_string()); + + params.push("notary_signature".to_string()); + params.push(self.notary_signature.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a PreviewError value +/// Converts Query Parameters representation (style=form, explode=false) to a NotarizedTransaction value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for PreviewError { +impl std::str::FromStr for NotarizedTransaction { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub message: Vec, + pub hash: Vec, + pub signed_intent: Vec, + pub notary_signature: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -2460,14 +3088,15 @@ impl std::str::FromStr for PreviewError { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing PreviewError".to_string()) + None => return std::result::Result::Err("Missing value while parsing NotarizedTransaction".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing PreviewError".to_string()) + "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), + "signed_intent" => intermediate_rep.signed_intent.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notary_signature" => intermediate_rep.notary_signature.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NotarizedTransaction".to_string()) } } @@ -2476,41 +3105,42 @@ impl std::str::FromStr for PreviewError { } // Use the intermediate representation to return the struct - std::result::Result::Ok(PreviewError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in PreviewError".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in PreviewError".to_string())?, + std::result::Result::Ok(NotarizedTransaction { + hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in NotarizedTransaction".to_string())?, + signed_intent: intermediate_rep.signed_intent.into_iter().next().ok_or("signed_intent missing in NotarizedTransaction".to_string())?, + notary_signature: intermediate_rep.notary_signature.into_iter().next().ok_or("notary_signature missing in NotarizedTransaction".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for PreviewError - value: {} is invalid {}", + format!("Invalid header value for NotarizedTransaction - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into PreviewError - {}", + format!("Unable to convert header value '{}' into NotarizedTransaction - {}", value, err)) } }, @@ -2524,100 +3154,54 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewRequest { - #[serde(rename = "network_identifier")] - pub network_identifier: models::NetworkIdentifier, - - /// A transaction manifest. Sbor encoded, and then hex encoded. - #[serde(rename = "manifest")] - pub manifest: String, - - /// A limit of cost units available for execution - #[serde(rename = "cost_unit_limit")] - pub cost_unit_limit: i32, - - /// A tip for the validator - #[serde(rename = "tip_percentage")] - pub tip_percentage: i32, - - /// A nonce value to use for execution - #[serde(rename = "nonce")] - pub nonce: i64, - - /// A list of public keys to be used as transaction signers, in a compressed format, hex encoded. - #[serde(rename = "signer_public_keys")] - pub signer_public_keys: Vec, +pub struct PreviewError { + #[serde(rename = "type")] + pub type_: String, - #[serde(rename = "flags")] - pub flags: models::TransactionPreviewRequestFlags, + #[serde(rename = "message")] + pub message: String, } -impl TransactionPreviewRequest { - pub fn new(network_identifier: models::NetworkIdentifier, manifest: String, cost_unit_limit: i32, tip_percentage: i32, nonce: i64, signer_public_keys: Vec, flags: models::TransactionPreviewRequestFlags, ) -> TransactionPreviewRequest { - TransactionPreviewRequest { - network_identifier: network_identifier, - manifest: manifest, - cost_unit_limit: cost_unit_limit, - tip_percentage: tip_percentage, - nonce: nonce, - signer_public_keys: signer_public_keys, - flags: flags, +impl PreviewError { + pub fn new(type_: String, message: String, ) -> PreviewError { + PreviewError { + type_: type_, + message: message, } } } -/// Converts the TransactionPreviewRequest value to the Query Parameters representation (style=form, explode=false) +/// Converts the PreviewError value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewRequest { +impl std::string::ToString for PreviewError { fn to_string(&self) -> String { let mut params: Vec = vec![]; - // Skipping network_identifier in query parameter serialization - - - params.push("manifest".to_string()); - params.push(self.manifest.to_string()); - - - params.push("cost_unit_limit".to_string()); - params.push(self.cost_unit_limit.to_string()); - - - params.push("tip_percentage".to_string()); - params.push(self.tip_percentage.to_string()); - - - params.push("nonce".to_string()); - params.push(self.nonce.to_string()); + params.push("type".to_string()); + params.push(self.type_.to_string()); - params.push("signer_public_keys".to_string()); - params.push(self.signer_public_keys.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - // Skipping flags in query parameter serialization + params.push("message".to_string()); + params.push(self.message.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequest value +/// Converts Query Parameters representation (style=form, explode=false) to a PreviewError value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewRequest { +impl std::str::FromStr for PreviewError { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub network_identifier: Vec, - pub manifest: Vec, - pub cost_unit_limit: Vec, - pub tip_percentage: Vec, - pub nonce: Vec, - pub signer_public_keys: Vec>, - pub flags: Vec, + pub type_: Vec, + pub message: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -2629,67 +3213,57 @@ impl std::str::FromStr for TransactionPreviewRequest { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequest".to_string()) + None => return std::result::Result::Err("Missing value while parsing PreviewError".to_string()) }; if let Some(key) = key_result { match key { - "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), - "manifest" => intermediate_rep.manifest.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), - "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), - "nonce" => intermediate_rep.nonce.push(::from_str(val).map_err(|x| format!("{}", x))?), - "signer_public_keys" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewRequest".to_string()), - "flags" => intermediate_rep.flags.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequest".to_string()) + "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), + "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing PreviewError".to_string()) } } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewRequest { - network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in TransactionPreviewRequest".to_string())?, - manifest: intermediate_rep.manifest.into_iter().next().ok_or("manifest missing in TransactionPreviewRequest".to_string())?, - cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in TransactionPreviewRequest".to_string())?, - tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in TransactionPreviewRequest".to_string())?, - nonce: intermediate_rep.nonce.into_iter().next().ok_or("nonce missing in TransactionPreviewRequest".to_string())?, - signer_public_keys: intermediate_rep.signer_public_keys.into_iter().next().ok_or("signer_public_keys missing in TransactionPreviewRequest".to_string())?, - flags: intermediate_rep.flags.into_iter().next().ok_or("flags missing in TransactionPreviewRequest".to_string())?, + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(PreviewError { + type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in PreviewError".to_string())?, + message: intermediate_rep.message.into_iter().next().ok_or("message missing in PreviewError".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewRequest - value: {} is invalid {}", + format!("Invalid header value for PreviewError - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewRequest - {}", + format!("Unable to convert header value '{}' into PreviewError - {}", value, err)) } }, @@ -2703,45 +3277,59 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewRequestFlags { - #[serde(rename = "unlimited_loan")] - pub unlimited_loan: bool, +pub struct SignedTransactionIntent { + #[serde(rename = "hash")] + pub hash: String, + + #[serde(rename = "intent")] + pub intent: models::TransactionIntent, + + #[serde(rename = "intent_signatures")] + pub intent_signatures: Vec, } -impl TransactionPreviewRequestFlags { - pub fn new(unlimited_loan: bool, ) -> TransactionPreviewRequestFlags { - TransactionPreviewRequestFlags { - unlimited_loan: unlimited_loan, +impl SignedTransactionIntent { + pub fn new(hash: String, intent: models::TransactionIntent, intent_signatures: Vec, ) -> SignedTransactionIntent { + SignedTransactionIntent { + hash: hash, + intent: intent, + intent_signatures: intent_signatures, } } } -/// Converts the TransactionPreviewRequestFlags value to the Query Parameters representation (style=form, explode=false) +/// Converts the SignedTransactionIntent value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewRequestFlags { +impl std::string::ToString for SignedTransactionIntent { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("unlimited_loan".to_string()); - params.push(self.unlimited_loan.to_string()); + params.push("hash".to_string()); + params.push(self.hash.to_string()); + + // Skipping intent in query parameter serialization + + // Skipping intent_signatures in query parameter serialization params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequestFlags value +/// Converts Query Parameters representation (style=form, explode=false) to a SignedTransactionIntent value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewRequestFlags { +impl std::str::FromStr for SignedTransactionIntent { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub unlimited_loan: Vec, + pub hash: Vec, + pub intent: Vec, + pub intent_signatures: Vec>, } let mut intermediate_rep = IntermediateRep::default(); @@ -2753,13 +3341,15 @@ impl std::str::FromStr for TransactionPreviewRequestFlags { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequestFlags".to_string()) + None => return std::result::Result::Err("Missing value while parsing SignedTransactionIntent".to_string()) }; if let Some(key) = key_result { match key { - "unlimited_loan" => intermediate_rep.unlimited_loan.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequestFlags".to_string()) + "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), + "intent" => intermediate_rep.intent.push(::from_str(val).map_err(|x| format!("{}", x))?), + "intent_signatures" => return std::result::Result::Err("Parsing a container in this style is not supported in SignedTransactionIntent".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing SignedTransactionIntent".to_string()) } } @@ -2768,40 +3358,42 @@ impl std::str::FromStr for TransactionPreviewRequestFlags { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewRequestFlags { - unlimited_loan: intermediate_rep.unlimited_loan.into_iter().next().ok_or("unlimited_loan missing in TransactionPreviewRequestFlags".to_string())?, + std::result::Result::Ok(SignedTransactionIntent { + hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in SignedTransactionIntent".to_string())?, + intent: intermediate_rep.intent.into_iter().next().ok_or("intent missing in SignedTransactionIntent".to_string())?, + intent_signatures: intermediate_rep.intent_signatures.into_iter().next().ok_or("intent_signatures missing in SignedTransactionIntent".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewRequestFlags - value: {} is invalid {}", + format!("Invalid header value for SignedTransactionIntent - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewRequestFlags - {}", + format!("Unable to convert header value '{}' into SignedTransactionIntent - {}", value, err)) } }, @@ -2815,87 +3407,115 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewResponse { - #[serde(rename = "transaction_status")] - pub transaction_status: models::TransactionStatus, +pub struct TransactionHeader { + #[serde(rename = "version")] + pub version: isize, - #[serde(rename = "transaction_fee")] - pub transaction_fee: models::FeeSummary, + #[serde(rename = "network")] + pub network: models::Network, - #[serde(rename = "logs")] - pub logs: Vec, + #[serde(rename = "start_epoch_inclusive")] + pub start_epoch_inclusive: String, - /// A list of new package addresses - #[serde(rename = "new_package_addresses")] - pub new_package_addresses: Vec, + #[serde(rename = "end_epoch_exclusive")] + pub end_epoch_exclusive: String, - /// A list of new component addresses - #[serde(rename = "new_component_addresses")] - pub new_component_addresses: Vec, + #[serde(rename = "nonce")] + pub nonce: String, - /// A list of new resource addresses - #[serde(rename = "new_resource_addresses")] - pub new_resource_addresses: Vec, + #[serde(rename = "notary_public_key")] + pub notary_public_key: String, + + #[serde(rename = "notary_as_signatory")] + pub notary_as_signatory: bool, + + #[serde(rename = "cost_unit_limit")] + pub cost_unit_limit: String, + + #[serde(rename = "tip_percentage")] + pub tip_percentage: String, } -impl TransactionPreviewResponse { - pub fn new(transaction_status: models::TransactionStatus, transaction_fee: models::FeeSummary, logs: Vec, new_package_addresses: Vec, new_component_addresses: Vec, new_resource_addresses: Vec, ) -> TransactionPreviewResponse { - TransactionPreviewResponse { - transaction_status: transaction_status, - transaction_fee: transaction_fee, - logs: logs, - new_package_addresses: new_package_addresses, - new_component_addresses: new_component_addresses, - new_resource_addresses: new_resource_addresses, +impl TransactionHeader { + pub fn new(version: isize, network: models::Network, start_epoch_inclusive: String, end_epoch_exclusive: String, nonce: String, notary_public_key: String, notary_as_signatory: bool, cost_unit_limit: String, tip_percentage: String, ) -> TransactionHeader { + TransactionHeader { + version: version, + network: network, + start_epoch_inclusive: start_epoch_inclusive, + end_epoch_exclusive: end_epoch_exclusive, + nonce: nonce, + notary_public_key: notary_public_key, + notary_as_signatory: notary_as_signatory, + cost_unit_limit: cost_unit_limit, + tip_percentage: tip_percentage, } } } -/// Converts the TransactionPreviewResponse value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionHeader value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewResponse { +impl std::string::ToString for TransactionHeader { fn to_string(&self) -> String { let mut params: Vec = vec![]; - // Skipping transaction_status in query parameter serialization - // Skipping transaction_fee in query parameter serialization + params.push("version".to_string()); + params.push(self.version.to_string()); - // Skipping logs in query parameter serialization + // Skipping network in query parameter serialization - params.push("new_package_addresses".to_string()); - params.push(self.new_package_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + params.push("start_epoch_inclusive".to_string()); + params.push(self.start_epoch_inclusive.to_string()); - params.push("new_component_addresses".to_string()); - params.push(self.new_component_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + params.push("end_epoch_exclusive".to_string()); + params.push(self.end_epoch_exclusive.to_string()); - params.push("new_resource_addresses".to_string()); - params.push(self.new_resource_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + params.push("nonce".to_string()); + params.push(self.nonce.to_string()); + + + params.push("notary_public_key".to_string()); + params.push(self.notary_public_key.to_string()); + + + params.push("notary_as_signatory".to_string()); + params.push(self.notary_as_signatory.to_string()); + + + params.push("cost_unit_limit".to_string()); + params.push(self.cost_unit_limit.to_string()); + + + params.push("tip_percentage".to_string()); + params.push(self.tip_percentage.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponse value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionHeader value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewResponse { +impl std::str::FromStr for TransactionHeader { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub transaction_status: Vec, - pub transaction_fee: Vec, - pub logs: Vec>, - pub new_package_addresses: Vec>, - pub new_component_addresses: Vec>, - pub new_resource_addresses: Vec>, + pub version: Vec, + pub network: Vec, + pub start_epoch_inclusive: Vec, + pub end_epoch_exclusive: Vec, + pub nonce: Vec, + pub notary_public_key: Vec, + pub notary_as_signatory: Vec, + pub cost_unit_limit: Vec, + pub tip_percentage: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -2907,18 +3527,21 @@ impl std::str::FromStr for TransactionPreviewResponse { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponse".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionHeader".to_string()) }; if let Some(key) = key_result { match key { - "transaction_status" => intermediate_rep.transaction_status.push(::from_str(val).map_err(|x| format!("{}", x))?), - "transaction_fee" => intermediate_rep.transaction_fee.push(::from_str(val).map_err(|x| format!("{}", x))?), - "logs" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "new_package_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "new_component_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "new_resource_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponse".to_string()) + "version" => intermediate_rep.version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "network" => intermediate_rep.network.push(::from_str(val).map_err(|x| format!("{}", x))?), + "start_epoch_inclusive" => intermediate_rep.start_epoch_inclusive.push(::from_str(val).map_err(|x| format!("{}", x))?), + "end_epoch_exclusive" => intermediate_rep.end_epoch_exclusive.push(::from_str(val).map_err(|x| format!("{}", x))?), + "nonce" => intermediate_rep.nonce.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notary_public_key" => intermediate_rep.notary_public_key.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notary_as_signatory" => intermediate_rep.notary_as_signatory.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), + "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionHeader".to_string()) } } @@ -2927,45 +3550,48 @@ impl std::str::FromStr for TransactionPreviewResponse { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewResponse { - transaction_status: intermediate_rep.transaction_status.into_iter().next().ok_or("transaction_status missing in TransactionPreviewResponse".to_string())?, - transaction_fee: intermediate_rep.transaction_fee.into_iter().next().ok_or("transaction_fee missing in TransactionPreviewResponse".to_string())?, - logs: intermediate_rep.logs.into_iter().next().ok_or("logs missing in TransactionPreviewResponse".to_string())?, - new_package_addresses: intermediate_rep.new_package_addresses.into_iter().next().ok_or("new_package_addresses missing in TransactionPreviewResponse".to_string())?, - new_component_addresses: intermediate_rep.new_component_addresses.into_iter().next().ok_or("new_component_addresses missing in TransactionPreviewResponse".to_string())?, - new_resource_addresses: intermediate_rep.new_resource_addresses.into_iter().next().ok_or("new_resource_addresses missing in TransactionPreviewResponse".to_string())?, + std::result::Result::Ok(TransactionHeader { + version: intermediate_rep.version.into_iter().next().ok_or("version missing in TransactionHeader".to_string())?, + network: intermediate_rep.network.into_iter().next().ok_or("network missing in TransactionHeader".to_string())?, + start_epoch_inclusive: intermediate_rep.start_epoch_inclusive.into_iter().next().ok_or("start_epoch_inclusive missing in TransactionHeader".to_string())?, + end_epoch_exclusive: intermediate_rep.end_epoch_exclusive.into_iter().next().ok_or("end_epoch_exclusive missing in TransactionHeader".to_string())?, + nonce: intermediate_rep.nonce.into_iter().next().ok_or("nonce missing in TransactionHeader".to_string())?, + notary_public_key: intermediate_rep.notary_public_key.into_iter().next().ok_or("notary_public_key missing in TransactionHeader".to_string())?, + notary_as_signatory: intermediate_rep.notary_as_signatory.into_iter().next().ok_or("notary_as_signatory missing in TransactionHeader".to_string())?, + cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in TransactionHeader".to_string())?, + tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in TransactionHeader".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewResponse - value: {} is invalid {}", + format!("Invalid header value for TransactionHeader - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewResponse - {}", + format!("Unable to convert header value '{}' into TransactionHeader - {}", value, err)) } }, @@ -2979,54 +3605,61 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewResponseLogsInner { - #[serde(rename = "level")] - pub level: String, +pub struct TransactionIntent { + #[serde(rename = "hash")] + pub hash: String, - #[serde(rename = "message")] - pub message: String, + #[serde(rename = "header")] + pub header: models::TransactionHeader, + + #[serde(rename = "manifest")] + pub manifest: String, } -impl TransactionPreviewResponseLogsInner { - pub fn new(level: String, message: String, ) -> TransactionPreviewResponseLogsInner { - TransactionPreviewResponseLogsInner { - level: level, - message: message, +impl TransactionIntent { + pub fn new(hash: String, header: models::TransactionHeader, manifest: String, ) -> TransactionIntent { + TransactionIntent { + hash: hash, + header: header, + manifest: manifest, } } } -/// Converts the TransactionPreviewResponseLogsInner value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionIntent value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewResponseLogsInner { +impl std::string::ToString for TransactionIntent { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("level".to_string()); - params.push(self.level.to_string()); + params.push("hash".to_string()); + params.push(self.hash.to_string()); + // Skipping header in query parameter serialization - params.push("message".to_string()); - params.push(self.message.to_string()); + + params.push("manifest".to_string()); + params.push(self.manifest.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponseLogsInner value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionIntent value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewResponseLogsInner { +impl std::str::FromStr for TransactionIntent { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub level: Vec, - pub message: Vec, + pub hash: Vec, + pub header: Vec, + pub manifest: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3038,14 +3671,15 @@ impl std::str::FromStr for TransactionPreviewResponseLogsInner { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponseLogsInner".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionIntent".to_string()) }; if let Some(key) = key_result { match key { - "level" => intermediate_rep.level.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponseLogsInner".to_string()) + "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), + "header" => intermediate_rep.header.push(::from_str(val).map_err(|x| format!("{}", x))?), + "manifest" => intermediate_rep.manifest.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionIntent".to_string()) } } @@ -3054,41 +3688,42 @@ impl std::str::FromStr for TransactionPreviewResponseLogsInner { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewResponseLogsInner { - level: intermediate_rep.level.into_iter().next().ok_or("level missing in TransactionPreviewResponseLogsInner".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in TransactionPreviewResponseLogsInner".to_string())?, + std::result::Result::Ok(TransactionIntent { + hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in TransactionIntent".to_string())?, + header: intermediate_rep.header.into_iter().next().ok_or("header missing in TransactionIntent".to_string())?, + manifest: intermediate_rep.manifest.into_iter().next().ok_or("manifest missing in TransactionIntent".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewResponseLogsInner - value: {} is invalid {}", + format!("Invalid header value for TransactionIntent - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewResponseLogsInner - {}", + format!("Unable to convert header value '{}' into TransactionIntent - {}", value, err)) } }, @@ -3102,45 +3737,100 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatus { - #[serde(rename = "type")] - pub type_: String, +pub struct TransactionPreviewRequest { + #[serde(rename = "network_identifier")] + pub network_identifier: models::NetworkIdentifier, + + /// A transaction manifest. Sbor encoded, and then hex encoded. + #[serde(rename = "manifest")] + pub manifest: String, + + /// A limit of cost units available for execution + #[serde(rename = "cost_unit_limit")] + pub cost_unit_limit: i32, + + /// A tip for the validator + #[serde(rename = "tip_percentage")] + pub tip_percentage: i32, + + /// A nonce value to use for execution + #[serde(rename = "nonce")] + pub nonce: i64, + + /// A list of public keys to be used as transaction signers, in a compressed format, hex encoded. + #[serde(rename = "signer_public_keys")] + pub signer_public_keys: Vec, + + #[serde(rename = "flags")] + pub flags: models::TransactionPreviewRequestFlags, } -impl TransactionStatus { - pub fn new(type_: String, ) -> TransactionStatus { - TransactionStatus { - type_: type_, +impl TransactionPreviewRequest { + pub fn new(network_identifier: models::NetworkIdentifier, manifest: String, cost_unit_limit: i32, tip_percentage: i32, nonce: i64, signer_public_keys: Vec, flags: models::TransactionPreviewRequestFlags, ) -> TransactionPreviewRequest { + TransactionPreviewRequest { + network_identifier: network_identifier, + manifest: manifest, + cost_unit_limit: cost_unit_limit, + tip_percentage: tip_percentage, + nonce: nonce, + signer_public_keys: signer_public_keys, + flags: flags, } } } -/// Converts the TransactionStatus value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatus { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; +/// Converts the TransactionPreviewRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for TransactionPreviewRequest { + fn to_string(&self) -> String { + let mut params: Vec = vec![]; + // Skipping network_identifier in query parameter serialization + + + params.push("manifest".to_string()); + params.push(self.manifest.to_string()); + + + params.push("cost_unit_limit".to_string()); + params.push(self.cost_unit_limit.to_string()); + + + params.push("tip_percentage".to_string()); + params.push(self.tip_percentage.to_string()); + + + params.push("nonce".to_string()); + params.push(self.nonce.to_string()); + - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("signer_public_keys".to_string()); + params.push(self.signer_public_keys.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + // Skipping flags in query parameter serialization params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatus value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequest value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatus { +impl std::str::FromStr for TransactionPreviewRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, + pub network_identifier: Vec, + pub manifest: Vec, + pub cost_unit_limit: Vec, + pub tip_percentage: Vec, + pub nonce: Vec, + pub signer_public_keys: Vec>, + pub flags: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3152,13 +3842,19 @@ impl std::str::FromStr for TransactionStatus { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatus".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequest".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatus".to_string()) + "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), + "manifest" => intermediate_rep.manifest.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), + "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), + "nonce" => intermediate_rep.nonce.push(::from_str(val).map_err(|x| format!("{}", x))?), + "signer_public_keys" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewRequest".to_string()), + "flags" => intermediate_rep.flags.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequest".to_string()) } } @@ -3167,40 +3863,46 @@ impl std::str::FromStr for TransactionStatus { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatus { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatus".to_string())?, + std::result::Result::Ok(TransactionPreviewRequest { + network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in TransactionPreviewRequest".to_string())?, + manifest: intermediate_rep.manifest.into_iter().next().ok_or("manifest missing in TransactionPreviewRequest".to_string())?, + cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in TransactionPreviewRequest".to_string())?, + tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in TransactionPreviewRequest".to_string())?, + nonce: intermediate_rep.nonce.into_iter().next().ok_or("nonce missing in TransactionPreviewRequest".to_string())?, + signer_public_keys: intermediate_rep.signer_public_keys.into_iter().next().ok_or("signer_public_keys missing in TransactionPreviewRequest".to_string())?, + flags: intermediate_rep.flags.into_iter().next().ok_or("flags missing in TransactionPreviewRequest".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatus - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewRequest - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatus - {}", + format!("Unable to convert header value '{}' into TransactionPreviewRequest - {}", value, err)) } }, @@ -3214,54 +3916,45 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusFailed { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "message")] - pub message: String, +pub struct TransactionPreviewRequestFlags { + #[serde(rename = "unlimited_loan")] + pub unlimited_loan: bool, } -impl TransactionStatusFailed { - pub fn new(type_: String, message: String, ) -> TransactionStatusFailed { - TransactionStatusFailed { - type_: type_, - message: message, +impl TransactionPreviewRequestFlags { + pub fn new(unlimited_loan: bool, ) -> TransactionPreviewRequestFlags { + TransactionPreviewRequestFlags { + unlimited_loan: unlimited_loan, } } } -/// Converts the TransactionStatusFailed value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionPreviewRequestFlags value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusFailed { +impl std::string::ToString for TransactionPreviewRequestFlags { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("message".to_string()); - params.push(self.message.to_string()); + params.push("unlimited_loan".to_string()); + params.push(self.unlimited_loan.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusFailed value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequestFlags value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusFailed { +impl std::str::FromStr for TransactionPreviewRequestFlags { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub message: Vec, + pub unlimited_loan: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3273,14 +3966,13 @@ impl std::str::FromStr for TransactionStatusFailed { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusFailed".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequestFlags".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusFailed".to_string()) + "unlimited_loan" => intermediate_rep.unlimited_loan.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequestFlags".to_string()) } } @@ -3289,41 +3981,40 @@ impl std::str::FromStr for TransactionStatusFailed { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusFailed { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatusFailed".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in TransactionStatusFailed".to_string())?, + std::result::Result::Ok(TransactionPreviewRequestFlags { + unlimited_loan: intermediate_rep.unlimited_loan.into_iter().next().ok_or("unlimited_loan missing in TransactionPreviewRequestFlags".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusFailed - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewRequestFlags - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusFailed - {}", + format!("Unable to convert header value '{}' into TransactionPreviewRequestFlags - {}", value, err)) } }, @@ -3337,45 +4028,111 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusRejected { - #[serde(rename = "type")] - pub type_: String, +pub struct TransactionPreviewResponse { + #[serde(rename = "transaction_status")] + pub transaction_status: models::TransactionStatus, + + #[serde(rename = "transaction_fee")] + pub transaction_fee: models::FeeSummary, + + #[serde(rename = "logs")] + pub logs: Vec, + + /// A list of new package addresses + #[serde(rename = "new_package_addresses")] + pub new_package_addresses: Vec, + + /// A list of new component addresses + #[serde(rename = "new_component_addresses")] + pub new_component_addresses: Vec, + + /// A list of new resource addresses + #[serde(rename = "new_resource_addresses")] + pub new_resource_addresses: Vec, + + #[serde(rename = "output")] + #[serde(skip_serializing_if="Option::is_none")] + pub output: Option>, + + #[serde(rename = "error_message")] + #[serde(skip_serializing_if="Option::is_none")] + pub error_message: Option, } -impl TransactionStatusRejected { - pub fn new(type_: String, ) -> TransactionStatusRejected { - TransactionStatusRejected { - type_: type_, +impl TransactionPreviewResponse { + pub fn new(transaction_status: models::TransactionStatus, transaction_fee: models::FeeSummary, logs: Vec, new_package_addresses: Vec, new_component_addresses: Vec, new_resource_addresses: Vec, ) -> TransactionPreviewResponse { + TransactionPreviewResponse { + transaction_status: transaction_status, + transaction_fee: transaction_fee, + logs: logs, + new_package_addresses: new_package_addresses, + new_component_addresses: new_component_addresses, + new_resource_addresses: new_resource_addresses, + output: None, + error_message: None, } } } -/// Converts the TransactionStatusRejected value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionPreviewResponse value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusRejected { +impl std::string::ToString for TransactionPreviewResponse { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping transaction_status in query parameter serialization - params.push("type".to_string()); - params.push(self.type_.to_string()); + // Skipping transaction_fee in query parameter serialization + + // Skipping logs in query parameter serialization + + + params.push("new_package_addresses".to_string()); + params.push(self.new_package_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + + params.push("new_component_addresses".to_string()); + params.push(self.new_component_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + + params.push("new_resource_addresses".to_string()); + params.push(self.new_resource_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + + if let Some(ref output) = self.output { + params.push("output".to_string()); + params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + } + + + if let Some(ref error_message) = self.error_message { + params.push("error_message".to_string()); + params.push(error_message.to_string()); + } params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusRejected value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponse value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusRejected { +impl std::str::FromStr for TransactionPreviewResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, + pub transaction_status: Vec, + pub transaction_fee: Vec, + pub logs: Vec>, + pub new_package_addresses: Vec>, + pub new_component_addresses: Vec>, + pub new_resource_addresses: Vec>, + pub output: Vec>, + pub error_message: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3387,13 +4144,20 @@ impl std::str::FromStr for TransactionStatusRejected { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusRejected".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponse".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusRejected".to_string()) + "transaction_status" => intermediate_rep.transaction_status.push(::from_str(val).map_err(|x| format!("{}", x))?), + "transaction_fee" => intermediate_rep.transaction_fee.push(::from_str(val).map_err(|x| format!("{}", x))?), + "logs" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "new_package_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "new_component_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "new_resource_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponse".to_string()) } } @@ -3402,40 +4166,47 @@ impl std::str::FromStr for TransactionStatusRejected { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusRejected { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatusRejected".to_string())?, + std::result::Result::Ok(TransactionPreviewResponse { + transaction_status: intermediate_rep.transaction_status.into_iter().next().ok_or("transaction_status missing in TransactionPreviewResponse".to_string())?, + transaction_fee: intermediate_rep.transaction_fee.into_iter().next().ok_or("transaction_fee missing in TransactionPreviewResponse".to_string())?, + logs: intermediate_rep.logs.into_iter().next().ok_or("logs missing in TransactionPreviewResponse".to_string())?, + new_package_addresses: intermediate_rep.new_package_addresses.into_iter().next().ok_or("new_package_addresses missing in TransactionPreviewResponse".to_string())?, + new_component_addresses: intermediate_rep.new_component_addresses.into_iter().next().ok_or("new_component_addresses missing in TransactionPreviewResponse".to_string())?, + new_resource_addresses: intermediate_rep.new_resource_addresses.into_iter().next().ok_or("new_resource_addresses missing in TransactionPreviewResponse".to_string())?, + output: intermediate_rep.output.into_iter().next(), + error_message: intermediate_rep.error_message.into_iter().next(), }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusRejected - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewResponse - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusRejected - {}", + format!("Unable to convert header value '{}' into TransactionPreviewResponse - {}", value, err)) } }, @@ -3449,54 +4220,54 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusSucceeded { - #[serde(rename = "type")] - pub type_: String, +pub struct TransactionPreviewResponseLogsInner { + #[serde(rename = "level")] + pub level: String, - #[serde(rename = "output")] - pub output: Vec, + #[serde(rename = "message")] + pub message: String, } -impl TransactionStatusSucceeded { - pub fn new(type_: String, output: Vec, ) -> TransactionStatusSucceeded { - TransactionStatusSucceeded { - type_: type_, - output: output, +impl TransactionPreviewResponseLogsInner { + pub fn new(level: String, message: String, ) -> TransactionPreviewResponseLogsInner { + TransactionPreviewResponseLogsInner { + level: level, + message: message, } } } -/// Converts the TransactionStatusSucceeded value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionPreviewResponseLogsInner value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusSucceeded { +impl std::string::ToString for TransactionPreviewResponseLogsInner { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("level".to_string()); + params.push(self.level.to_string()); - params.push("output".to_string()); - params.push(self.output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + params.push("message".to_string()); + params.push(self.message.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusSucceeded value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponseLogsInner value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusSucceeded { +impl std::str::FromStr for TransactionPreviewResponseLogsInner { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub output: Vec>, + pub level: Vec, + pub message: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3508,14 +4279,14 @@ impl std::str::FromStr for TransactionStatusSucceeded { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusSucceeded".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponseLogsInner".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionStatusSucceeded".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusSucceeded".to_string()) + "level" => intermediate_rep.level.push(::from_str(val).map_err(|x| format!("{}", x))?), + "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponseLogsInner".to_string()) } } @@ -3524,41 +4295,41 @@ impl std::str::FromStr for TransactionStatusSucceeded { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusSucceeded { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatusSucceeded".to_string())?, - output: intermediate_rep.output.into_iter().next().ok_or("output missing in TransactionStatusSucceeded".to_string())?, + std::result::Result::Ok(TransactionPreviewResponseLogsInner { + level: intermediate_rep.level.into_iter().next().ok_or("level missing in TransactionPreviewResponseLogsInner".to_string())?, + message: intermediate_rep.message.into_iter().next().ok_or("message missing in TransactionPreviewResponseLogsInner".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusSucceeded - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewResponseLogsInner - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusSucceeded - {}", + format!("Unable to convert header value '{}' into TransactionPreviewResponseLogsInner - {}", value, err)) } }, @@ -3572,45 +4343,74 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusSucceededAllOf { +pub struct TransactionReceipt { + #[serde(rename = "status")] + pub status: models::TransactionStatus, + + #[serde(rename = "fee_summary")] + pub fee_summary: models::FeeSummary, + #[serde(rename = "output")] - pub output: Vec, + #[serde(skip_serializing_if="Option::is_none")] + pub output: Option>, + + #[serde(rename = "error_message")] + #[serde(skip_serializing_if="Option::is_none")] + pub error_message: Option, } -impl TransactionStatusSucceededAllOf { - pub fn new(output: Vec, ) -> TransactionStatusSucceededAllOf { - TransactionStatusSucceededAllOf { - output: output, +impl TransactionReceipt { + pub fn new(status: models::TransactionStatus, fee_summary: models::FeeSummary, ) -> TransactionReceipt { + TransactionReceipt { + status: status, + fee_summary: fee_summary, + output: None, + error_message: None, } } } -/// Converts the TransactionStatusSucceededAllOf value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionReceipt value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusSucceededAllOf { +impl std::string::ToString for TransactionReceipt { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping status in query parameter serialization + + // Skipping fee_summary in query parameter serialization + + + if let Some(ref output) = self.output { + params.push("output".to_string()); + params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + } - params.push("output".to_string()); - params.push(self.output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + if let Some(ref error_message) = self.error_message { + params.push("error_message".to_string()); + params.push(error_message.to_string()); + } params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusSucceededAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionReceipt value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusSucceededAllOf { +impl std::str::FromStr for TransactionReceipt { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { + pub status: Vec, + pub fee_summary: Vec, pub output: Vec>, + pub error_message: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3622,13 +4422,16 @@ impl std::str::FromStr for TransactionStatusSucceededAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusSucceededAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionReceipt".to_string()) }; if let Some(key) = key_result { match key { - "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionStatusSucceededAllOf".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusSucceededAllOf".to_string()) + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| format!("{}", x))?), + "fee_summary" => intermediate_rep.fee_summary.push(::from_str(val).map_err(|x| format!("{}", x))?), + "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionReceipt".to_string()), + "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionReceipt".to_string()) } } @@ -3637,40 +4440,43 @@ impl std::str::FromStr for TransactionStatusSucceededAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusSucceededAllOf { - output: intermediate_rep.output.into_iter().next().ok_or("output missing in TransactionStatusSucceededAllOf".to_string())?, + std::result::Result::Ok(TransactionReceipt { + status: intermediate_rep.status.into_iter().next().ok_or("status missing in TransactionReceipt".to_string())?, + fee_summary: intermediate_rep.fee_summary.into_iter().next().ok_or("fee_summary missing in TransactionReceipt".to_string())?, + output: intermediate_rep.output.into_iter().next(), + error_message: intermediate_rep.error_message.into_iter().next(), }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusSucceededAllOf - value: {} is invalid {}", + format!("Invalid header value for TransactionReceipt - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusSucceededAllOf - {}", + format!("Unable to convert header value '{}' into TransactionReceipt - {}", value, err)) } }, @@ -3682,6 +4488,46 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// The status of the transaction +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum TransactionStatus { + #[serde(rename = "succeeded")] + SUCCEEDED, + #[serde(rename = "failed")] + FAILED, + #[serde(rename = "rejected")] + REJECTED, +} + +impl std::fmt::Display for TransactionStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + TransactionStatus::SUCCEEDED => write!(f, "succeeded"), + TransactionStatus::FAILED => write!(f, "failed"), + TransactionStatus::REJECTED => write!(f, "rejected"), + } + } +} + +impl std::str::FromStr for TransactionStatus { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "succeeded" => std::result::Result::Ok(TransactionStatus::SUCCEEDED), + "failed" => std::result::Result::Ok(TransactionStatus::FAILED), + "rejected" => std::result::Result::Ok(TransactionStatus::REJECTED), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct TransactionSubmitRequest { diff --git a/state-manager/core-api-server/src/core_api/generated/server.rs b/state-manager/core-api-server/src/core_api/generated/server.rs index 7a460eb267..e42de67de5 100644 --- a/state-manager/core-api-server/src/core_api/generated/server.rs +++ b/state-manager/core-api-server/src/core_api/generated/server.rs @@ -24,7 +24,8 @@ type ServiceFuture = BoxFuture<'static, Result, crate::core_api:: use crate::core_api::generated::{Api, StatusNetworkConfigurationPostResponse, TransactionPreviewPostResponse, - TransactionSubmitPostResponse + TransactionSubmitPostResponse, + TransactionsPostResponse }; mod paths { @@ -34,13 +35,15 @@ mod paths { pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(vec![ r"^/core/status/network-configuration$", r"^/core/transaction/preview$", - r"^/core/transaction/submit$" + r"^/core/transaction/submit$", + r"^/core/transactions$" ]) .expect("Unable to create global regex set"); } pub(crate) static ID_STATUS_NETWORK_CONFIGURATION: usize = 0; pub(crate) static ID_TRANSACTION_PREVIEW: usize = 1; pub(crate) static ID_TRANSACTION_SUBMIT: usize = 2; + pub(crate) static ID_TRANSACTIONS: usize = 3; } pub struct MakeService where @@ -169,14 +172,14 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, - StatusNetworkConfigurationPostResponse::AnErrorOccurred + StatusNetworkConfigurationPostResponse::ServerError (body) => { *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for STATUS_NETWORK_CONFIGURATION_POST_AN_ERROR_OCCURRED")); + .expect("Unable to create Content-Type header for STATUS_NETWORK_CONFIGURATION_POST_SERVER_ERROR")); let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, @@ -254,14 +257,25 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, - TransactionPreviewPostResponse::AnErrorOccurred + TransactionPreviewPostResponse::ClientError + (body) + => { + *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTION_PREVIEW_POST_CLIENT_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionPreviewPostResponse::ServerError (body) => { *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for TRANSACTION_PREVIEW_POST_AN_ERROR_OCCURRED")); + .expect("Unable to create Content-Type header for TRANSACTION_PREVIEW_POST_SERVER_ERROR")); let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, @@ -345,14 +359,25 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, - TransactionSubmitPostResponse::AnErrorOccurred + TransactionSubmitPostResponse::ClientError + (body) + => { + *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTION_SUBMIT_POST_CLIENT_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionSubmitPostResponse::ServerError (body) => { *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for TRANSACTION_SUBMIT_POST_AN_ERROR_OCCURRED")); + .expect("Unable to create Content-Type header for TRANSACTION_SUBMIT_POST_SERVER_ERROR")); let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, @@ -374,9 +399,112 @@ impl hyper::service::Service<(Request, C)> for Service where } }, + // TransactionsPost - POST /transactions + &hyper::Method::POST if path.matched(paths::ID_TRANSACTIONS) => { + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + let result = body.into_raw().await; + match result { + Ok(body) => { + let mut unused_elements = Vec::new(); + let param_committed_transactions_request: Option = if !body.is_empty() { + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_committed_transactions_request) => param_committed_transactions_request, + Err(e) => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Couldn't parse body parameter CommittedTransactionsRequest - doesn't match schema: {}", e))) + .expect("Unable to create Bad Request response for invalid body parameter CommittedTransactionsRequest due to schema")), + } + } else { + None + }; + let param_committed_transactions_request = match param_committed_transactions_request { + Some(param_committed_transactions_request) => param_committed_transactions_request, + None => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from("Missing required body parameter CommittedTransactionsRequest")) + .expect("Unable to create Bad Request response for missing body parameter CommittedTransactionsRequest")), + }; + + let result = api_impl.transactions_post( + param_committed_transactions_request, + &context + ).await; + let mut response = Response::new(Body::empty()); + response.headers_mut().insert( + HeaderName::from_static("x-span-id"), + HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + .expect("Unable to create X-Span-ID header value")); + + if !unused_elements.is_empty() { + response.headers_mut().insert( + HeaderName::from_static("warning"), + HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) + .expect("Unable to create Warning header value")); + } + + match result { + Ok(rsp) => match rsp { + TransactionsPostResponse::CommittedTransactionsResponse + (body) + => { + *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTIONS_POST_COMMITTED_TRANSACTIONS_RESPONSE")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionsPostResponse::ClientError + (body) + => { + *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTIONS_POST_CLIENT_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionsPostResponse::ServerError + (body) + => { + *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTIONS_POST_SERVER_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; + *response.body_mut() = Body::from("An internal error occurred"); + }, + } + + Ok(response) + }, + Err(e) => Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Couldn't read body parameter CommittedTransactionsRequest: {}", e))) + .expect("Unable to create Bad Request response due to unable to read body parameter CommittedTransactionsRequest")), + } + }, + _ if path.matched(paths::ID_STATUS_NETWORK_CONFIGURATION) => method_not_allowed(), _ if path.matched(paths::ID_TRANSACTION_PREVIEW) => method_not_allowed(), _ if path.matched(paths::ID_TRANSACTION_SUBMIT) => method_not_allowed(), + _ if path.matched(paths::ID_TRANSACTIONS) => method_not_allowed(), _ => Ok(Response::builder().status(StatusCode::NOT_FOUND) .body(Body::empty()) .expect("Unable to create Not Found response")) @@ -396,6 +524,8 @@ impl RequestParser for ApiRequestParser { &hyper::Method::POST if path.matched(paths::ID_TRANSACTION_PREVIEW) => Some("TransactionPreviewPost"), // TransactionSubmitPost - POST /transaction/submit &hyper::Method::POST if path.matched(paths::ID_TRANSACTION_SUBMIT) => Some("TransactionSubmitPost"), + // TransactionsPost - POST /transactions + &hyper::Method::POST if path.matched(paths::ID_TRANSACTIONS) => Some("TransactionsPost"), _ => None, } } diff --git a/state-manager/core-api-server/src/core_api/mod.rs b/state-manager/core-api-server/src/core_api/mod.rs index 5190d084d1..c50fc6f9fb 100644 --- a/state-manager/core-api-server/src/core_api/mod.rs +++ b/state-manager/core-api-server/src/core_api/mod.rs @@ -62,7 +62,11 @@ * permissions under this License. */ +mod network_configuration; +mod preview; pub mod server; +mod transactions; + #[allow(unused)] #[rustfmt::skip] diff --git a/state-manager/core-api-server/src/core_api/network_configuration.rs b/state-manager/core-api-server/src/core_api/network_configuration.rs new file mode 100644 index 0000000000..1f68a1bc46 --- /dev/null +++ b/state-manager/core-api-server/src/core_api/network_configuration.rs @@ -0,0 +1,48 @@ +use crate::core_api::generated::models::*; +use crate::core_api::generated::{StatusNetworkConfigurationPostResponse, API_VERSION}; +use scrypto::address::get_network_hrp_set; +use state_manager::StateManager; +use std::sync::{Arc, Mutex}; +use swagger::ApiError; + +pub(crate) fn handle_network_configuration( + state_manager: Arc>, +) -> Result { + handle_network_configuration_internal(state_manager) + .map(StatusNetworkConfigurationPostResponse::NetworkConfiguration) + .or_else(Ok) +} + +fn handle_network_configuration_internal( + state_manager: Arc>, +) -> Result { + let locked_state_manager = state_manager + .lock() + .map_err(|_| server_error("Internal server error (state manager lock)"))?; + let network = locked_state_manager.network(); + + let hrp_set = get_network_hrp_set(network); + + Ok(NetworkConfigurationResponse { + version: NetworkConfigurationResponseVersion { + core_version: env!("CARGO_PKG_VERSION").to_string(), + api_version: API_VERSION.to_string(), + }, + network_identifier: NetworkIdentifier { + network: format!("{:?}", network), + }, + bech32_human_readable_parts: Bech32Hrps { + account_hrp: hrp_set.account_component.to_string(), + validator_hrp: "TODO".to_string(), + node_hrp: "TODO".to_string(), + resource_hrp_suffix: hrp_set.resource.to_string(), + }, + }) +} + +fn server_error(message: &str) -> StatusNetworkConfigurationPostResponse { + StatusNetworkConfigurationPostResponse::ServerError(ErrorResponse::new( + 500, + message.to_string(), + )) +} diff --git a/state-manager/core-api-server/src/core_api/preview.rs b/state-manager/core-api-server/src/core_api/preview.rs new file mode 100644 index 0000000000..19c995145c --- /dev/null +++ b/state-manager/core-api-server/src/core_api/preview.rs @@ -0,0 +1,177 @@ +use crate::core_api::generated::models::*; +use crate::core_api::generated::{models, TransactionPreviewPostResponse}; +use radix_engine::transaction::{PreviewResult, TransactionStatus}; +use scrypto::address::Bech32Encoder; +use scrypto::crypto::EcdsaPublicKey; +use scrypto::prelude::scrypto_decode; +use state_manager::{PreviewRequest, StateManager}; +use std::sync::{Arc, Mutex}; +use swagger::ApiError; +use transaction::model::{PreviewFlags, TransactionManifest}; + +pub(crate) fn handle_preview( + state_manager: Arc>, + request: TransactionPreviewRequest, +) -> Result { + handle_preview_internal(state_manager, request) + .map(TransactionPreviewPostResponse::TransactionPreviewResponse) + .or_else(Ok) +} + +fn handle_preview_internal( + state_manager: Arc>, + request: TransactionPreviewRequest, +) -> Result { + let preview_request = parse_preview_request(request)?; + + let mut locked_state_manager = state_manager + .lock() + .map_err(|_| server_error("Internal server error (state manager lock)"))?; + + let result = locked_state_manager + .preview(preview_request) + .map_err(|e| client_error(&format!("{:?}", e)))?; + + let bech32_encoder = Bech32Encoder::new_from_network(locked_state_manager.network()); + + to_api_response(result, bech32_encoder) +} + +fn parse_preview_request( + request: TransactionPreviewRequest, +) -> Result { + let cost_unit_limit: u32 = request + .cost_unit_limit + .try_into() + .map_err(|_| client_error("Invalid cost_unit_limit"))?; + + let tip_percentage: u32 = request + .tip_percentage + .try_into() + .map_err(|_| client_error("Invalid tip_percentage"))?; + + let nonce: u64 = request + .nonce + .try_into() + .map_err(|_| client_error("Invalid nonce"))?; + + let manifest = hex::decode(request.manifest) + .map(|manifest_bytes| { + scrypto_decode::(&manifest_bytes) + .map_err(|_| client_error("Invalid manifest")) + }) + .map_err(|_| client_error("Invalid manifest (malformed hex)"))??; + + let signer_public_keys: Vec = request + .signer_public_keys + .into_iter() + .flat_map(|s| { + hex::decode(s).map(|pub_key_bytes| { + EcdsaPublicKey::try_from(&pub_key_bytes[..]) + .map_err(|_| client_error("Invalid signer public key")) + .map_err(|_| client_error("Invalid signer public key (malformed hex)")) + }) + }) + .collect::, TransactionPreviewPostResponse>>()?; + + Ok(PreviewRequest { + manifest, + cost_unit_limit, + tip_percentage, + nonce, + signer_public_keys, + flags: PreviewFlags { + unlimited_loan: request.flags.unlimited_loan, + }, + }) +} + +fn to_api_response( + result: PreviewResult, + bech32_encoder: Bech32Encoder, +) -> Result { + let (status, output, error_message) = match result.receipt.status { + TransactionStatus::Succeeded(output) => { + let output_hex = output.into_iter().map(hex::encode).collect(); + (models::TransactionStatus::SUCCEEDED, Some(output_hex), None) + } + TransactionStatus::Failed(error) => ( + models::TransactionStatus::FAILED, + None, + Some(format!("{:?}", error)), + ), + TransactionStatus::Rejected => (models::TransactionStatus::REJECTED, None, None), + }; + + let fee_summary = &result.receipt.fee_summary; + + let logs = result + .receipt + .application_logs + .into_iter() + .map(|(level, message)| TransactionPreviewResponseLogsInner { + level: level.to_string(), + message, + }) + .collect(); + + let new_package_addresses = result + .receipt + .new_package_addresses + .into_iter() + .map(|addr| { + bech32_encoder + .encode_package_address(&addr) + .map_err(|_| server_error("Unexpected error, failed to encode package address")) + }) + .collect::, TransactionPreviewPostResponse>>()?; + + let new_component_addresses = result + .receipt + .new_component_addresses + .into_iter() + .map(|addr| { + bech32_encoder + .encode_component_address(&addr) + .map_err(|_| server_error("Unexpected error, failed to encode component address")) + }) + .collect::, TransactionPreviewPostResponse>>()?; + + let new_resource_addresses = result + .receipt + .new_resource_addresses + .into_iter() + .map(|addr| { + bech32_encoder + .encode_resource_address(&addr) + .map_err(|_| server_error("Unexpected error, failed to encode resource address")) + }) + .collect::, TransactionPreviewPostResponse>>()?; + + Ok(TransactionPreviewResponse { + transaction_status: status, + transaction_fee: FeeSummary { + loan_fully_repaid: fee_summary.loan_fully_repaid, + cost_unit_limit: fee_summary.cost_unit_limit.to_string(), + cost_unit_consumed: fee_summary.cost_unit_consumed.to_string(), + cost_unit_price: fee_summary.cost_unit_price.to_string(), + tip_percentage: fee_summary.tip_percentage.to_string(), + xrd_burned: fee_summary.burned.to_string(), + xrd_tipped: fee_summary.tipped.to_string(), + }, + logs, + new_package_addresses, + new_component_addresses, + new_resource_addresses, + output, + error_message, + }) +} + +fn client_error(message: &str) -> TransactionPreviewPostResponse { + TransactionPreviewPostResponse::ClientError(ErrorResponse::new(400, message.to_string())) +} + +fn server_error(message: &str) -> TransactionPreviewPostResponse { + TransactionPreviewPostResponse::ServerError(ErrorResponse::new(500, message.to_string())) +} diff --git a/state-manager/core-api-server/src/core_api/server.rs b/state-manager/core-api-server/src/core_api/server.rs index a17e535b77..ccd197b9c5 100644 --- a/state-manager/core-api-server/src/core_api/server.rs +++ b/state-manager/core-api-server/src/core_api/server.rs @@ -62,27 +62,23 @@ * permissions under this License. */ -use crate::core_api::generated::models; -use crate::core_api::generated::models::{ - Bech32Hrps, NetworkConfigurationResponse, NetworkConfigurationResponseVersion, - NetworkIdentifier, -}; use crate::core_api::generated::server::MakeService; +use crate::core_api::generated::{models, TransactionsPostResponse}; use crate::core_api::generated::{ Api, StatusNetworkConfigurationPostResponse, TransactionPreviewPostResponse, - TransactionSubmitPostResponse, API_VERSION, + TransactionSubmitPostResponse, }; use async_trait::async_trait; use state_manager::StateManager; -use scrypto::address::get_network_hrp_set; - use std::future::Future; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; +use crate::core_api::generated::models::CommittedTransactionsRequest; +use crate::core_api::{network_configuration, preview, transactions}; use scrypto::prelude::*; use swagger::ApiError; use swagger::EmptyContext; @@ -133,50 +129,31 @@ where &self, _context: &C, ) -> Result { - let network = &self - .state_manager - .lock() - .expect("Can't acquire state manager lock") - .network() - .clone(); - - let hrp_set = get_network_hrp_set(network); - - Ok( - StatusNetworkConfigurationPostResponse::NetworkConfiguration( - NetworkConfigurationResponse { - version: NetworkConfigurationResponseVersion { - core_version: env!("CARGO_PKG_VERSION").to_string(), - api_version: API_VERSION.to_string(), - }, - network_identifier: NetworkIdentifier { - network: format!("{:?}", network), - }, - bech32_human_readable_parts: Bech32Hrps { - account_hrp: hrp_set.account_component.to_string(), - validator_hrp: "TODO".to_string(), - node_hrp: "TODO".to_string(), - resource_hrp_suffix: hrp_set.resource.to_string(), - }, - }, - ), - ) + network_configuration::handle_network_configuration(self.state_manager.clone()) } async fn transaction_preview_post( &self, - _transaction_preview_request: models::TransactionPreviewRequest, + request: models::TransactionPreviewRequest, _context: &C, ) -> Result { - Err(ApiError("To be implemented".into())) + preview::handle_preview(self.state_manager.clone(), request) } async fn transaction_submit_post( &self, - _transaction_submit_request: models::TransactionSubmitRequest, + request: models::TransactionSubmitRequest, _context: &C, ) -> Result { - Err(ApiError("To be implemented".into())) + transactions::handle_submit_transaction(self.state_manager.clone(), request) + } + + async fn transactions_post( + &self, + request: CommittedTransactionsRequest, + _context: &C, + ) -> Result { + transactions::handle_transactions(self.state_manager.clone(), request) } } diff --git a/state-manager/core-api-server/src/core_api/transactions.rs b/state-manager/core-api-server/src/core_api/transactions.rs new file mode 100644 index 0000000000..255e21f2a0 --- /dev/null +++ b/state-manager/core-api-server/src/core_api/transactions.rs @@ -0,0 +1,174 @@ +use crate::core_api::generated::models::*; +use crate::core_api::generated::{TransactionSubmitPostResponse, TransactionsPostResponse}; +use scrypto::buffer::scrypto_decode; +use scrypto::crypto::sha256_twice; +use scrypto::prelude::scrypto_encode; +use state_manager::{MempoolError, StateManager, TId, TemporaryTransactionReceipt, Transaction, CommitRequest}; +use std::sync::{Arc, Mutex}; +use swagger::ApiError; +use transaction::model::NotarizedTransaction as EngineNotarizedTransaction; + +pub(crate) fn handle_submit_transaction( + state_manager: Arc>, + request: TransactionSubmitRequest, +) -> Result { + handle_submit_transaction_internal(state_manager, request) + .map(TransactionSubmitPostResponse::TransactionSubmitResponse) + .or_else(Ok) +} + +fn handle_submit_transaction_internal( + state_manager: Arc>, + request: TransactionSubmitRequest, +) -> Result { + let transaction_bytes = hex::decode(request.notarized_transaction) + .map_err(|_| submit_client_error("Invalid transaction (malformed hex)"))?; + + let tid = sha256_twice(transaction_bytes.clone()); + + let transaction = Transaction { + payload: transaction_bytes, + id: TId { + bytes: tid.to_vec(), + }, + }; + + let mut locked_state_manager = state_manager + .lock() + .map_err(|_| submit_server_error("Internal server error (state manager lock)"))?; + + let result = locked_state_manager + .mempool() + .add_transaction(transaction.clone()); // TODO: no need to clone once commit removed + + // TODO: remove me + locked_state_manager.commit(CommitRequest { + transactions: vec![transaction], + state_version: 0, + proof: vec![] + }); + + match result { + Ok(_) => Ok(TransactionSubmitResponse::new(false)), + Err(MempoolError::Duplicate) => Ok(TransactionSubmitResponse::new(true)), + Err(MempoolError::Full { + current_size: _, + max_size: _, + }) => Err(submit_server_error("Mempool is full")), + Err(MempoolError::TransactionValidationError(err)) => Err(submit_client_error(&format!( + "Transaction validation error: {:?}", + err + ))), + } +} + +fn submit_client_error(message: &str) -> TransactionSubmitPostResponse { + TransactionSubmitPostResponse::ClientError(ErrorResponse::new(400, message.to_string())) +} + +fn submit_server_error(message: &str) -> TransactionSubmitPostResponse { + TransactionSubmitPostResponse::ServerError(ErrorResponse::new(500, message.to_string())) +} + +pub(crate) fn handle_transactions( + state_manager: Arc>, + request: CommittedTransactionsRequest, +) -> Result { + handle_transactions_internal(state_manager, request) + .map(TransactionsPostResponse::CommittedTransactionsResponse) + .or_else(Ok) +} + +fn handle_transactions_internal( + state_manager: Arc>, + request: CommittedTransactionsRequest, +) -> Result { + let mut locked_state_manager = state_manager + .lock() + .map_err(|_| transactions_server_error("Internal server error (state manager lock)"))?; + + let txns = locked_state_manager + .transaction_store() + .get_some_random_txs(); // TODO: fixme + + let api_txns = txns + .into_iter() + .map(|(tx, receipt)| { + scrypto_decode(tx) + .map(|notarized_tx| to_api_committed_transaction(notarized_tx, receipt.clone())) + .map_err(|_| transactions_server_error("Invalid committed txn payload")) + }) + .collect::, TransactionsPostResponse>>()?; + + Ok(CommittedTransactionsResponse { + state_version: request.state_version, + transactions: api_txns, + }) +} + +fn to_api_committed_transaction( + tx: EngineNotarizedTransaction, + _receipt: TemporaryTransactionReceipt, +) -> CommittedTransaction { + let tx_hash = tx.hash(); + let signed_intent = tx.signed_intent; + let signed_intent_hash = signed_intent.hash(); + let intent = signed_intent.intent; + let intent_hash = intent.hash(); + let header = intent.header; + + CommittedTransaction { + notarized_transaction: NotarizedTransaction { + hash: tx_hash.to_string(), + signed_intent: SignedTransactionIntent { + hash: signed_intent_hash.to_string(), + intent: TransactionIntent { + hash: intent_hash.to_string(), + header: TransactionHeader { + version: header.version as isize, + network: Network { + id: "1".to_string(), // TODO: fixme + name: format!("{:?}", header.network), + }, + start_epoch_inclusive: header.start_epoch_inclusive.to_string(), + end_epoch_exclusive: header.end_epoch_exclusive.to_string(), + nonce: header.nonce.to_string(), + notary_public_key: header.notary_public_key.to_string(), + notary_as_signatory: header.notary_as_signatory, + cost_unit_limit: header.cost_unit_limit.to_string(), + tip_percentage: header.tip_percentage.to_string(), + }, + manifest: hex::encode(scrypto_encode(&intent.manifest)), + }, + intent_signatures: signed_intent + .intent_signatures + .into_iter() + .map(|(public_key, signature)| IntentSignature { + public_key: public_key.to_string(), + signature: signature.to_string(), + }) + .collect(), + }, + notary_signature: tx.notary_signature.to_string(), + }, + receipt: TransactionReceipt { + status: TransactionStatus::SUCCEEDED, // TODO: fixme (needs receipt) + fee_summary: FeeSummary { + // TODO: fixme + loan_fully_repaid: true, + cost_unit_limit: "0".to_string(), + cost_unit_consumed: "0".to_string(), + cost_unit_price: "0".to_string(), + tip_percentage: "0".to_string(), + xrd_burned: "0".to_string(), + xrd_tipped: "0".to_string(), + }, + output: Some(vec!["00".to_string()]), // TODO: fixme (needs receipt) + error_message: None, // TODO: fixme (needs receipt) + }, + } +} + +fn transactions_server_error(message: &str) -> TransactionsPostResponse { + TransactionsPostResponse::ServerError(ErrorResponse::new(500, message.to_string())) +} diff --git a/state-manager/state-manager/src/jni/state_computer/dto.rs b/state-manager/state-manager/src/jni/state_computer/dto.rs deleted file mode 100644 index 76150e8f37..0000000000 --- a/state-manager/state-manager/src/jni/state_computer/dto.rs +++ /dev/null @@ -1,160 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -use radix_engine::fee::FeeSummary; -use radix_engine::transaction::{PreviewResult, TransactionStatus}; -use sbor::{Decode, Encode, TypeId}; -use scrypto::component::{ComponentAddress, PackageAddress}; -use scrypto::core::Level; -use scrypto::math::Decimal; -use scrypto::prelude::ResourceAddress; - -use crate::result::StateManagerResult; -use crate::types::PreviewError; - -#[derive(Debug, PartialEq, Eq, TypeId, Encode, Decode)] -pub struct PreviewErrorJava { - message: String, -} - -impl From for StateManagerResult { - fn from(err: PreviewError) -> Self { - let msg: String = match err { - PreviewError::InvalidManifest => "Invalid manifest".to_string(), - PreviewError::InvalidSignerPublicKey => "Invalid signer public key".to_string(), - PreviewError::EngineError(engine_preview_error) => { - format!("Preview execution failed: {:?}", engine_preview_error) - } - }; - Ok(PreviewErrorJava { message: msg }) - } -} - -#[derive(Debug, TypeId, Encode, Decode)] -pub enum TransactionStatusJava { - Rejected, - Succeeded(Vec>), - Failed(String), -} - -#[derive(Debug, TypeId, Encode, Decode)] -pub struct FeeSummaryJava { - pub loan_fully_repaid: bool, - pub cost_unit_limit: u32, - pub cost_units_consumed: u32, - pub cost_unit_price: Decimal, - pub tip_percentage: u32, - pub burned: Decimal, - pub tipped: Decimal, -} - -impl From for FeeSummaryJava { - fn from(fee_summary: FeeSummary) -> Self { - FeeSummaryJava { - loan_fully_repaid: fee_summary.loan_fully_repaid, - cost_unit_limit: fee_summary.cost_unit_limit, - cost_units_consumed: fee_summary.cost_unit_consumed, - cost_unit_price: fee_summary.cost_unit_price, - tip_percentage: fee_summary.tip_percentage, - burned: fee_summary.burned, - tipped: fee_summary.tipped, - } - } -} - -#[derive(Debug, TypeId, Encode, Decode)] -pub struct PreviewResultJava { - status: TransactionStatusJava, - fee_summary: FeeSummaryJava, - application_logs: Vec<(Level, String)>, - new_package_addresses: Vec, - new_component_addresses: Vec, - new_resource_addresses: Vec, -} - -impl From for PreviewResultJava { - fn from(result: PreviewResult) -> Self { - let receipt = result.receipt; - PreviewResultJava { - status: receipt.status.into(), - fee_summary: receipt.fee_summary.into(), - application_logs: receipt.application_logs, - new_package_addresses: receipt.new_package_addresses, - new_component_addresses: receipt.new_component_addresses, - new_resource_addresses: receipt.new_resource_addresses, - } - } -} - -impl From for TransactionStatusJava { - fn from(status: TransactionStatus) -> Self { - match status { - TransactionStatus::Rejected => TransactionStatusJava::Rejected, - TransactionStatus::Succeeded(output) => TransactionStatusJava::Succeeded(output), - TransactionStatus::Failed(error) => { - TransactionStatusJava::Failed(format!("{:?}", error)) - } - } - } -} diff --git a/state-manager/state-manager/src/jni/state_computer/mod.rs b/state-manager/state-manager/src/jni/state_computer/mod.rs index 9783c49150..93f5b51fcc 100644 --- a/state-manager/state-manager/src/jni/state_computer/mod.rs +++ b/state-manager/state-manager/src/jni/state_computer/mod.rs @@ -62,10 +62,7 @@ * permissions under this License. */ -mod dto; - use crate::jni::dtos::JavaStructure; -use dto::*; use jni::objects::{JClass, JObject}; use jni::sys::jbyteArray; use jni::JNIEnv; @@ -73,8 +70,8 @@ use scrypto::prelude::*; use crate::jni::state_manager::JNIStateManager; use crate::jni::utils::*; -use crate::result::{ResultStateManagerMaps, StateManagerResult}; -use crate::types::{CommitRequest, PreviewRequest, Transaction}; +use crate::result::StateManagerResult; +use crate::types::{CommitRequest, Transaction}; // // JNI Interface @@ -106,34 +103,6 @@ fn do_verify( Ok(result.is_ok()) } -#[no_mangle] -extern "system" fn Java_com_radixdlt_statecomputer_RustStateComputer_preview( - env: JNIEnv, - _class: JClass, - j_state_manager: JObject, - request_payload: jbyteArray, -) -> jbyteArray { - let ret = do_preview(&env, j_state_manager, request_payload).to_java(); - jni_slice_to_jbytearray(&env, &ret) -} - -fn do_preview( - env: &JNIEnv, - j_state_manager: JObject, - request_payload: jbyteArray, -) -> StateManagerResult> { - let state_manager = JNIStateManager::get_state_manager(env, j_state_manager); - let request_payload: Vec = jni_jbytearray_to_vector(env, request_payload)?; - let preview_request = PreviewRequest::from_java(&request_payload)?; - let preview_result: Result = state_manager - .lock() - .expect("Can't acquire a state manager mutex lock") - .preview(&preview_request) - .map(|result| result.into()) - .map_err_sm(|err| err.into())?; - Ok(preview_result) -} - #[no_mangle] extern "system" fn Java_com_radixdlt_statecomputer_RustStateComputer_commit( env: JNIEnv, diff --git a/state-manager/state-manager/src/lib.rs b/state-manager/state-manager/src/lib.rs index 961d12ce64..f89e9a97ee 100644 --- a/state-manager/state-manager/src/lib.rs +++ b/state-manager/state-manager/src/lib.rs @@ -71,4 +71,7 @@ mod store; mod transaction_builder; mod types; +pub use mempool::MempoolError; pub use state_manager::StateManager; +pub use store::TemporaryTransactionReceipt; +pub use types::{PreviewRequest, TId, Transaction, CommitRequest}; diff --git a/state-manager/state-manager/src/state_manager.rs b/state-manager/state-manager/src/state_manager.rs index b64ac3b8fc..094800dca4 100644 --- a/state-manager/state-manager/src/state_manager.rs +++ b/state-manager/state-manager/src/state_manager.rs @@ -66,24 +66,23 @@ use crate::jni::dtos::*; use crate::mempool::{Mempool, MempoolConfig}; use crate::query::ResourceAccounter; use crate::store::{ProofStore, TransactionStore}; -use crate::types::{CommitRequest, PreviewError, PreviewRequest, Transaction}; +use crate::types::{CommitRequest, PreviewRequest, Transaction}; use radix_engine::constants::{ DEFAULT_COST_UNIT_LIMIT, DEFAULT_COST_UNIT_PRICE, DEFAULT_MAX_CALL_DEPTH, DEFAULT_SYSTEM_LOAN, }; use radix_engine::ledger::{QueryableSubstateStore, ReadableSubstateStore, WriteableSubstateStore}; use radix_engine::transaction::{ - ExecutionConfig, PreviewExecutor, PreviewResult, TransactionExecutor, TransactionReceipt, + ExecutionConfig, PreviewError, PreviewExecutor, PreviewResult, TransactionExecutor, + TransactionReceipt, }; use radix_engine::wasm::{DefaultWasmEngine, WasmInstrumenter}; use scrypto::core::Network; use scrypto::engine::types::RENodeId; use scrypto::prelude::*; -use scrypto::prelude::{scrypto_decode, EcdsaPublicKey}; use std::collections::HashMap; use transaction::errors::TransactionValidationError; use transaction::model::{ - PreviewFlags, PreviewIntent, TransactionHeader, TransactionIntent, TransactionManifest, - ValidatedTransaction, + PreviewFlags, PreviewIntent, TransactionHeader, TransactionIntent, ValidatedTransaction, }; use transaction::signing::EcdsaPrivateKey; use transaction::validation::{TestIntentHashManager, TransactionValidator, ValidationConfig}; @@ -98,7 +97,7 @@ pub trait StateManager { txn: &Transaction, ) -> Result; - fn preview(&mut self, preview_request: &PreviewRequest) -> Result; + fn preview(&mut self, preview_request: PreviewRequest) -> Result; fn get_component_resources( &self, @@ -156,18 +155,7 @@ impl Result { - let manifest: TransactionManifest = - scrypto_decode(&preview_request.manifest).map_err(|_| PreviewError::InvalidManifest)?; - - let signer_public_keys: Result, PreviewError> = preview_request - .signer_public_keys - .iter() - .map(|pk| { - EcdsaPublicKey::try_from(&pk[..]).map_err(|_| PreviewError::InvalidSignerPublicKey) - }) - .collect(); - + fn preview(&mut self, preview_request: PreviewRequest) -> Result { // not really used for preview let notary_private_key = EcdsaPrivateKey::from_u64(2).unwrap(); @@ -184,24 +172,21 @@ impl> useage in some of the substates which does not play well /// TODO: with the babylon node multithreaded structures. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct TemporaryTransactionReceipt { pub result: String, pub new_package_addresses: Vec, @@ -116,4 +116,13 @@ impl TransactionStore { pub fn get_transaction(&self, tid: &TId) -> &(Vec, TemporaryTransactionReceipt) { self.in_memory_store.get(tid).expect("Transaction missing") } + + // TODO: remove me! + pub fn get_some_random_txs(&self) -> Vec<&(Vec, TemporaryTransactionReceipt)> { + self.in_memory_store + .values() + .next() + .map(|tx| vec![tx]) + .unwrap_or_default() + } } diff --git a/state-manager/state-manager/src/store/mod.rs b/state-manager/state-manager/src/store/mod.rs index 79190d0981..92d50597af 100644 --- a/state-manager/state-manager/src/store/mod.rs +++ b/state-manager/state-manager/src/store/mod.rs @@ -66,4 +66,4 @@ mod in_memory_proof_store; mod in_memory_transaction_store; pub use in_memory_proof_store::ProofStore; -pub use in_memory_transaction_store::TransactionStore; +pub use in_memory_transaction_store::{TemporaryTransactionReceipt, TransactionStore}; diff --git a/state-manager/state-manager/src/types.rs b/state-manager/state-manager/src/types.rs index e5b045eb27..eff790a865 100644 --- a/state-manager/state-manager/src/types.rs +++ b/state-manager/state-manager/src/types.rs @@ -62,9 +62,9 @@ * permissions under this License. */ -use radix_engine::transaction::PreviewError as EnginePreviewError; use sbor::{Decode, Encode, TypeId}; -use transaction::model::PreviewFlags; +use scrypto::crypto::EcdsaPublicKey; +use transaction::model::{PreviewFlags, TransactionManifest}; #[derive(Debug, PartialEq, Eq, Hash, Clone, Decode, Encode, TypeId)] pub struct TId { @@ -79,21 +79,14 @@ pub struct Transaction { #[derive(Debug, PartialEq, Eq, Clone, Decode, Encode, TypeId)] pub struct PreviewRequest { - pub manifest: Vec, + pub manifest: TransactionManifest, pub cost_unit_limit: u32, pub tip_percentage: u32, pub nonce: u64, - pub signer_public_keys: Vec>, + pub signer_public_keys: Vec, pub flags: PreviewFlags, } -#[derive(Debug)] -pub enum PreviewError { - InvalidManifest, - InvalidSignerPublicKey, - EngineError(EnginePreviewError), -} - #[derive(Debug, PartialEq, Eq, Clone, Decode, Encode, TypeId)] pub struct CommitRequest { pub transactions: Vec, From 61ab66d40f4d151a1cfd9d91e438666124eb5478 Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Fri, 26 Aug 2022 15:14:00 +0200 Subject: [PATCH 2/7] Network configuration: return only network hrp suffix --- .../java/com/radixdlt/api/CoreApiServer.java | 6 +- .../core-api-server/core-api-spec.yaml | 22 +-- .../src/core_api/generated/models.rs | 164 ++---------------- .../src/core_api/network_configuration.rs | 13 +- 4 files changed, 19 insertions(+), 186 deletions(-) diff --git a/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java b/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java index 98702d6011..f240f7d601 100644 --- a/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java +++ b/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java @@ -77,9 +77,9 @@ public final class CoreApiServer { /** * Stores a pointer to the rust core api server across JNI calls. In the JNI model, this is - * equivalent to the CoreApiServer "owning" the rust core api server memory. On each call into Rust, - * we map the rustCoreApiServerPointer onto a concrete implementation in Rust land, and it uses - * that to access all state and make calls. + * equivalent to the CoreApiServer "owning" the rust core api server memory. On each call into + * Rust, we map the rustCoreApiServerPointer onto a concrete implementation in Rust land, and it + * uses that to access all state and make calls. */ @SuppressWarnings("unused") private final long rustCoreApiServerPointer = 0; diff --git a/state-manager/core-api-server/core-api-spec.yaml b/state-manager/core-api-server/core-api-spec.yaml index 27f4157624..6d094af79d 100644 --- a/state-manager/core-api-server/core-api-spec.yaml +++ b/state-manager/core-api-server/core-api-spec.yaml @@ -392,7 +392,7 @@ components: required: - version - network_identifier - - bech32_human_readable_parts + - network_hrp_suffix properties: version: description: Different versions regarding the node, network and api. @@ -408,25 +408,9 @@ components: network_identifier: "$ref": "#/components/schemas/NetworkIdentifier" description: The name of the network. - bech32_human_readable_parts: - "$ref": "#/components/schemas/Bech32HRPs" - description: The unique bech32 hrps used for addressing. - Bech32HRPs: - type: object - required: - - account_hrp - - validator_hrp - - node_hrp - - resource_hrp_suffix - properties: - account_hrp: - type: string - validator_hrp: - type: string - node_hrp: - type: string - resource_hrp_suffix: + network_hrp_suffix: type: string + description: The network suffix used for bech32 hrps used for addressing. ################################ # REQUEST: /transaction/submit # ################################ diff --git a/state-manager/core-api-server/src/core_api/generated/models.rs b/state-manager/core-api-server/src/core_api/generated/models.rs index 4e642cc912..688c156f13 100644 --- a/state-manager/core-api-server/src/core_api/generated/models.rs +++ b/state-manager/core-api-server/src/core_api/generated/models.rs @@ -4,151 +4,6 @@ use crate::core_api::generated::models; use crate::core_api::generated::header; -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct Bech32Hrps { - #[serde(rename = "account_hrp")] - pub account_hrp: String, - - #[serde(rename = "validator_hrp")] - pub validator_hrp: String, - - #[serde(rename = "node_hrp")] - pub node_hrp: String, - - #[serde(rename = "resource_hrp_suffix")] - pub resource_hrp_suffix: String, - -} - -impl Bech32Hrps { - pub fn new(account_hrp: String, validator_hrp: String, node_hrp: String, resource_hrp_suffix: String, ) -> Bech32Hrps { - Bech32Hrps { - account_hrp: account_hrp, - validator_hrp: validator_hrp, - node_hrp: node_hrp, - resource_hrp_suffix: resource_hrp_suffix, - } - } -} - -/// Converts the Bech32Hrps value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for Bech32Hrps { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("account_hrp".to_string()); - params.push(self.account_hrp.to_string()); - - - params.push("validator_hrp".to_string()); - params.push(self.validator_hrp.to_string()); - - - params.push("node_hrp".to_string()); - params.push(self.node_hrp.to_string()); - - - params.push("resource_hrp_suffix".to_string()); - params.push(self.resource_hrp_suffix.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a Bech32Hrps value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for Bech32Hrps { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub account_hrp: Vec, - pub validator_hrp: Vec, - pub node_hrp: Vec, - pub resource_hrp_suffix: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing Bech32Hrps".to_string()) - }; - - if let Some(key) = key_result { - match key { - "account_hrp" => intermediate_rep.account_hrp.push(::from_str(val).map_err(|x| format!("{}", x))?), - "validator_hrp" => intermediate_rep.validator_hrp.push(::from_str(val).map_err(|x| format!("{}", x))?), - "node_hrp" => intermediate_rep.node_hrp.push(::from_str(val).map_err(|x| format!("{}", x))?), - "resource_hrp_suffix" => intermediate_rep.resource_hrp_suffix.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing Bech32Hrps".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(Bech32Hrps { - account_hrp: intermediate_rep.account_hrp.into_iter().next().ok_or("account_hrp missing in Bech32Hrps".to_string())?, - validator_hrp: intermediate_rep.validator_hrp.into_iter().next().ok_or("validator_hrp missing in Bech32Hrps".to_string())?, - node_hrp: intermediate_rep.node_hrp.into_iter().next().ok_or("node_hrp missing in Bech32Hrps".to_string())?, - resource_hrp_suffix: intermediate_rep.resource_hrp_suffix.into_iter().next().ok_or("resource_hrp_suffix missing in Bech32Hrps".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for Bech32Hrps - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into Bech32Hrps - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct CommittedTransaction { @@ -2322,17 +2177,18 @@ pub struct NetworkConfigurationResponse { #[serde(rename = "network_identifier")] pub network_identifier: models::NetworkIdentifier, - #[serde(rename = "bech32_human_readable_parts")] - pub bech32_human_readable_parts: models::Bech32Hrps, + /// The network suffix used for bech32 hrps used for addressing. + #[serde(rename = "network_hrp_suffix")] + pub network_hrp_suffix: String, } impl NetworkConfigurationResponse { - pub fn new(version: models::NetworkConfigurationResponseVersion, network_identifier: models::NetworkIdentifier, bech32_human_readable_parts: models::Bech32Hrps, ) -> NetworkConfigurationResponse { + pub fn new(version: models::NetworkConfigurationResponseVersion, network_identifier: models::NetworkIdentifier, network_hrp_suffix: String, ) -> NetworkConfigurationResponse { NetworkConfigurationResponse { version: version, network_identifier: network_identifier, - bech32_human_readable_parts: bech32_human_readable_parts, + network_hrp_suffix: network_hrp_suffix, } } } @@ -2347,7 +2203,9 @@ impl std::string::ToString for NetworkConfigurationResponse { // Skipping network_identifier in query parameter serialization - // Skipping bech32_human_readable_parts in query parameter serialization + + params.push("network_hrp_suffix".to_string()); + params.push(self.network_hrp_suffix.to_string()); params.join(",").to_string() } @@ -2365,7 +2223,7 @@ impl std::str::FromStr for NetworkConfigurationResponse { struct IntermediateRep { pub version: Vec, pub network_identifier: Vec, - pub bech32_human_readable_parts: Vec, + pub network_hrp_suffix: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -2384,7 +2242,7 @@ impl std::str::FromStr for NetworkConfigurationResponse { match key { "version" => intermediate_rep.version.push(::from_str(val).map_err(|x| format!("{}", x))?), "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), - "bech32_human_readable_parts" => intermediate_rep.bech32_human_readable_parts.push(::from_str(val).map_err(|x| format!("{}", x))?), + "network_hrp_suffix" => intermediate_rep.network_hrp_suffix.push(::from_str(val).map_err(|x| format!("{}", x))?), _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponse".to_string()) } } @@ -2397,7 +2255,7 @@ impl std::str::FromStr for NetworkConfigurationResponse { std::result::Result::Ok(NetworkConfigurationResponse { version: intermediate_rep.version.into_iter().next().ok_or("version missing in NetworkConfigurationResponse".to_string())?, network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in NetworkConfigurationResponse".to_string())?, - bech32_human_readable_parts: intermediate_rep.bech32_human_readable_parts.into_iter().next().ok_or("bech32_human_readable_parts missing in NetworkConfigurationResponse".to_string())?, + network_hrp_suffix: intermediate_rep.network_hrp_suffix.into_iter().next().ok_or("network_hrp_suffix missing in NetworkConfigurationResponse".to_string())?, }) } } diff --git a/state-manager/core-api-server/src/core_api/network_configuration.rs b/state-manager/core-api-server/src/core_api/network_configuration.rs index 1fb6b57553..453b96f849 100644 --- a/state-manager/core-api-server/src/core_api/network_configuration.rs +++ b/state-manager/core-api-server/src/core_api/network_configuration.rs @@ -1,6 +1,5 @@ use crate::core_api::generated::models::*; use crate::core_api::generated::{StatusNetworkConfigurationPostResponse, API_VERSION}; -use scrypto::address::{EntityType, HrpSet}; use state_manager::jni::state_manager::ActualStateManager; use std::sync::{Arc, Mutex}; use swagger::ApiError; @@ -20,7 +19,6 @@ fn handle_network_configuration_internal( .lock() .map_err(|_| server_error("Internal server error (state manager lock)"))?; let network = locked_state_manager.network.clone(); - let hrp_set: HrpSet = (&network).into(); Ok(NetworkConfigurationResponse { version: NetworkConfigurationResponseVersion { @@ -28,16 +26,9 @@ fn handle_network_configuration_internal( api_version: API_VERSION.to_string(), }, network_identifier: NetworkIdentifier { - network: format!("{:?}", network), - }, - bech32_human_readable_parts: Bech32Hrps { - account_hrp: hrp_set - .get_entity_hrp(&EntityType::AccountComponent) - .to_string(), - validator_hrp: "TODO".to_string(), - node_hrp: "TODO".to_string(), - resource_hrp_suffix: hrp_set.get_entity_hrp(&EntityType::Resource).to_string(), + network: network.logical_name, }, + network_hrp_suffix: network.hrp_suffix, }) } From 0db942427fbe99a9795ee87cb9fab8a9748ae72e Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Mon, 29 Aug 2022 15:42:55 +0200 Subject: [PATCH 3/7] Better error handling --- .../core-api-server/core-api-spec.yaml | 98 +- .../core-api-server/src/core_api/errors.rs | 22 + .../src/core_api/generated/models.rs | 2035 ++--------------- .../core-api-server/src/core_api/mod.rs | 1 + .../src/core_api/network_configuration.rs | 30 +- .../core-api-server/src/core_api/preview.rs | 77 +- .../core-api-server/src/core_api/server.rs | 16 +- .../src/core_api/transactions.rs | 111 +- 8 files changed, 354 insertions(+), 2036 deletions(-) create mode 100644 state-manager/core-api-server/src/core_api/errors.rs diff --git a/state-manager/core-api-server/core-api-spec.yaml b/state-manager/core-api-server/core-api-spec.yaml index 6d094af79d..184b72cc5f 100644 --- a/state-manager/core-api-server/core-api-spec.yaml +++ b/state-manager/core-api-server/core-api-spec.yaml @@ -162,10 +162,12 @@ components: "$ref": "#/components/schemas/FeeSummary" output: type: array + nullable: true items: type: string error_message: type: string + nullable: true NotarizedTransaction: type: object required: @@ -249,6 +251,7 @@ components: tip_percentage: type: string NetworkIdentifier: + description: The name of the network. type: object required: - network @@ -264,102 +267,20 @@ components: - message properties: code: - description: A numeric code corresponding to the given error type, roughly aligned with HTTP Status Code semantics (eg 400/404/500). + description: A numeric code corresponding to the given error type. type: integer message: description: A human-readable error message. type: string - details: - description: A structured/typed details object. - $ref: "#/components/schemas/CoreErrorDetails" trace_id: description: A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. type: string - CoreErrorDetails: - type: object - required: - - type - properties: - type: - type: string - discriminator: - propertyName: type - mapping: - NetworkNotSupportedError: "#/components/schemas/NetworkNotSupportedError" - InternalServerError: "#/components/schemas/InternalServerError" - InvalidJsonError: "#/components/schemas/InvalidJsonError" - InvalidHexError: "#/components/schemas/InvalidHexError" - MempoolFullError: "#/components/schemas/MempoolFullError" - InvalidTransactionError: "#/components/schemas/InvalidTransactionError" - PreviewError: "#/components/schemas/PreviewError" - NetworkNotSupportedError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - supported_networks - properties: - supported_networks: - type: array - items: - $ref: "#/components/schemas/NetworkIdentifier" - InternalServerError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - properties: - exception: - type: string - cause: - type: string - InvalidJsonError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - properties: - cause: - type: string - InvalidHexError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - invalid_hex - properties: - invalid_hex: - type: string - MempoolFullError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - mempool_transaction_count - properties: - mempool_transaction_count: - type: integer - format: int64 - InvalidTransactionError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - message - properties: - message: - type: string - PreviewError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - message - properties: - message: - type: string + nullable: true ######################################### # GENERAL / SHARED MODELS - Transaction # ######################################### FeeSummary: + description: Fees paid type: object required: - loan_fully_repaid @@ -407,7 +328,6 @@ components: type: string network_identifier: "$ref": "#/components/schemas/NetworkIdentifier" - description: The name of the network. network_hrp_suffix: type: string description: The network suffix used for bech32 hrps used for addressing. @@ -422,7 +342,6 @@ components: properties: network_identifier: "$ref": "#/components/schemas/NetworkIdentifier" - description: The name of the network. notarized_transaction: description: A notarized transaction encoded in the Radix transaction format, and then hex encoded. type: string @@ -451,7 +370,6 @@ components: properties: network_identifier: "$ref": "#/components/schemas/NetworkIdentifier" - description: The name of the network. manifest: description: A transaction manifest. Sbor encoded, and then hex encoded. type: string @@ -490,7 +408,6 @@ components: "$ref": "#/components/schemas/TransactionStatus" transaction_fee: "$ref": "#/components/schemas/FeeSummary" - description: Fees to be paid logs: type: array items: @@ -520,10 +437,12 @@ components: type: string output: type: array + nullable: true items: type: string error_message: type: string + nullable: true ########################## # REQUEST: /transactions # ########################## @@ -538,7 +457,6 @@ components: properties: network_identifier: "$ref": "#/components/schemas/NetworkIdentifier" - description: The name of the network state_version: type: string limit: diff --git a/state-manager/core-api-server/src/core_api/errors.rs b/state-manager/core-api-server/src/core_api/errors.rs new file mode 100644 index 0000000000..2ed289b185 --- /dev/null +++ b/state-manager/core-api-server/src/core_api/errors.rs @@ -0,0 +1,22 @@ +use crate::core_api::generated::models::ErrorResponse; + +pub(crate) enum RequestHandlingError { + ClientError(ErrorResponse), + ServerError(ErrorResponse), +} + +pub(crate) fn client_error(code: isize, message: &str) -> RequestHandlingError { + RequestHandlingError::ClientError(ErrorResponse::new(code, message.to_string())) +} + +pub(crate) fn server_error(code: isize, message: &str) -> RequestHandlingError { + RequestHandlingError::ServerError(ErrorResponse::new(code, message.to_string())) +} + +pub(crate) mod common_server_errors { + use crate::core_api::errors::{server_error, RequestHandlingError}; + + pub(crate) fn state_manager_lock_error() -> RequestHandlingError { + server_error(0, "Internal server error: state manager lock") + } +} diff --git a/state-manager/core-api-server/src/core_api/generated/models.rs b/state-manager/core-api-server/src/core_api/generated/models.rs index 688c156f13..af9a39bd10 100644 --- a/state-manager/core-api-server/src/core_api/generated/models.rs +++ b/state-manager/core-api-server/src/core_api/generated/models.rs @@ -390,122 +390,10 @@ impl std::convert::TryFrom for header::IntoHeaderVal } -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct CoreErrorDetails { - #[serde(rename = "type")] - pub type_: String, - -} - -impl CoreErrorDetails { - pub fn new(type_: String, ) -> CoreErrorDetails { - CoreErrorDetails { - type_: type_, - } - } -} - -/// Converts the CoreErrorDetails value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for CoreErrorDetails { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a CoreErrorDetails value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for CoreErrorDetails { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing CoreErrorDetails".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing CoreErrorDetails".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(CoreErrorDetails { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in CoreErrorDetails".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for CoreErrorDetails - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into CoreErrorDetails - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct ErrorResponse { - /// A numeric code corresponding to the given error type, roughly aligned with HTTP Status Code semantics (eg 400/404/500). + /// A numeric code corresponding to the given error type. #[serde(rename = "code")] pub code: isize, @@ -513,14 +401,12 @@ pub struct ErrorResponse { #[serde(rename = "message")] pub message: String, - #[serde(rename = "details")] - #[serde(skip_serializing_if="Option::is_none")] - pub details: Option, - /// A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. #[serde(rename = "trace_id")] + #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] + #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub trace_id: Option, + pub trace_id: Option>, } @@ -529,7 +415,6 @@ impl ErrorResponse { ErrorResponse { code: code, message: message, - details: None, trace_id: None, } } @@ -549,12 +434,10 @@ impl std::string::ToString for ErrorResponse { params.push("message".to_string()); params.push(self.message.to_string()); - // Skipping details in query parameter serialization - if let Some(ref trace_id) = self.trace_id { params.push("trace_id".to_string()); - params.push(trace_id.to_string()); + params.push(trace_id.as_ref().map_or("null".to_string(), |x| x.to_string())); } params.join(",").to_string() @@ -573,7 +456,6 @@ impl std::str::FromStr for ErrorResponse { struct IntermediateRep { pub code: Vec, pub message: Vec, - pub details: Vec, pub trace_id: Vec, } @@ -593,8 +475,7 @@ impl std::str::FromStr for ErrorResponse { match key { "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| format!("{}", x))?), "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - "details" => intermediate_rep.details.push(::from_str(val).map_err(|x| format!("{}", x))?), - "trace_id" => intermediate_rep.trace_id.push(::from_str(val).map_err(|x| format!("{}", x))?), + "trace_id" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ErrorResponse".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing ErrorResponse".to_string()) } } @@ -607,8 +488,7 @@ impl std::str::FromStr for ErrorResponse { std::result::Result::Ok(ErrorResponse { code: intermediate_rep.code.into_iter().next().ok_or("code missing in ErrorResponse".to_string())?, message: intermediate_rep.message.into_iter().next().ok_or("message missing in ErrorResponse".to_string())?, - details: intermediate_rep.details.into_iter().next(), - trace_id: intermediate_rep.trace_id.into_iter().next(), + trace_id: std::result::Result::Err("Nullable types not supported in ErrorResponse".to_string())?, }) } } @@ -652,6 +532,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// Fees paid #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct FeeSummary { @@ -955,69 +836,60 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InternalServerError { - #[serde(rename = "type")] - pub type_: String, +pub struct NetworkConfigurationResponse { + #[serde(rename = "version")] + pub version: models::NetworkConfigurationResponseVersion, - #[serde(rename = "exception")] - #[serde(skip_serializing_if="Option::is_none")] - pub exception: Option, + #[serde(rename = "network_identifier")] + pub network_identifier: models::NetworkIdentifier, - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, + /// The network suffix used for bech32 hrps used for addressing. + #[serde(rename = "network_hrp_suffix")] + pub network_hrp_suffix: String, } -impl InternalServerError { - pub fn new(type_: String, ) -> InternalServerError { - InternalServerError { - type_: type_, - exception: None, - cause: None, +impl NetworkConfigurationResponse { + pub fn new(version: models::NetworkConfigurationResponseVersion, network_identifier: models::NetworkIdentifier, network_hrp_suffix: String, ) -> NetworkConfigurationResponse { + NetworkConfigurationResponse { + version: version, + network_identifier: network_identifier, + network_hrp_suffix: network_hrp_suffix, } } } -/// Converts the InternalServerError value to the Query Parameters representation (style=form, explode=false) +/// Converts the NetworkConfigurationResponse value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InternalServerError { +impl std::string::ToString for NetworkConfigurationResponse { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping version in query parameter serialization - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - if let Some(ref exception) = self.exception { - params.push("exception".to_string()); - params.push(exception.to_string()); - } + // Skipping network_identifier in query parameter serialization - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } + params.push("network_hrp_suffix".to_string()); + params.push(self.network_hrp_suffix.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InternalServerError value +/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponse value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InternalServerError { +impl std::str::FromStr for NetworkConfigurationResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub exception: Vec, - pub cause: Vec, + pub version: Vec, + pub network_identifier: Vec, + pub network_hrp_suffix: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1029,15 +901,15 @@ impl std::str::FromStr for InternalServerError { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InternalServerError".to_string()) + None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponse".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "exception" => intermediate_rep.exception.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InternalServerError".to_string()) + "version" => intermediate_rep.version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), + "network_hrp_suffix" => intermediate_rep.network_hrp_suffix.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponse".to_string()) } } @@ -1046,42 +918,42 @@ impl std::str::FromStr for InternalServerError { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InternalServerError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InternalServerError".to_string())?, - exception: intermediate_rep.exception.into_iter().next(), - cause: intermediate_rep.cause.into_iter().next(), + std::result::Result::Ok(NetworkConfigurationResponse { + version: intermediate_rep.version.into_iter().next().ok_or("version missing in NetworkConfigurationResponse".to_string())?, + network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in NetworkConfigurationResponse".to_string())?, + network_hrp_suffix: intermediate_rep.network_hrp_suffix.into_iter().next().ok_or("network_hrp_suffix missing in NetworkConfigurationResponse".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InternalServerError - value: {} is invalid {}", + format!("Invalid header value for NetworkConfigurationResponse - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InternalServerError - {}", + format!("Unable to convert header value '{}' into NetworkConfigurationResponse - {}", value, err)) } }, @@ -1093,62 +965,57 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// Different versions regarding the node, network and api. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InternalServerErrorAllOf { - #[serde(rename = "exception")] - #[serde(skip_serializing_if="Option::is_none")] - pub exception: Option, +pub struct NetworkConfigurationResponseVersion { + #[serde(rename = "core_version")] + pub core_version: String, - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, + #[serde(rename = "api_version")] + pub api_version: String, } -impl InternalServerErrorAllOf { - pub fn new() -> InternalServerErrorAllOf { - InternalServerErrorAllOf { - exception: None, - cause: None, +impl NetworkConfigurationResponseVersion { + pub fn new(core_version: String, api_version: String, ) -> NetworkConfigurationResponseVersion { + NetworkConfigurationResponseVersion { + core_version: core_version, + api_version: api_version, } } } -/// Converts the InternalServerErrorAllOf value to the Query Parameters representation (style=form, explode=false) +/// Converts the NetworkConfigurationResponseVersion value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InternalServerErrorAllOf { +impl std::string::ToString for NetworkConfigurationResponseVersion { fn to_string(&self) -> String { let mut params: Vec = vec![]; - if let Some(ref exception) = self.exception { - params.push("exception".to_string()); - params.push(exception.to_string()); - } + params.push("core_version".to_string()); + params.push(self.core_version.to_string()); - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } + params.push("api_version".to_string()); + params.push(self.api_version.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InternalServerErrorAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponseVersion value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InternalServerErrorAllOf { +impl std::str::FromStr for NetworkConfigurationResponseVersion { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub exception: Vec, - pub cause: Vec, + pub core_version: Vec, + pub api_version: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1160,14 +1027,14 @@ impl std::str::FromStr for InternalServerErrorAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InternalServerErrorAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponseVersion".to_string()) }; if let Some(key) = key_result { match key { - "exception" => intermediate_rep.exception.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InternalServerErrorAllOf".to_string()) + "core_version" => intermediate_rep.core_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "api_version" => intermediate_rep.api_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponseVersion".to_string()) } } @@ -1176,41 +1043,41 @@ impl std::str::FromStr for InternalServerErrorAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InternalServerErrorAllOf { - exception: intermediate_rep.exception.into_iter().next(), - cause: intermediate_rep.cause.into_iter().next(), + std::result::Result::Ok(NetworkConfigurationResponseVersion { + core_version: intermediate_rep.core_version.into_iter().next().ok_or("core_version missing in NetworkConfigurationResponseVersion".to_string())?, + api_version: intermediate_rep.api_version.into_iter().next().ok_or("api_version missing in NetworkConfigurationResponseVersion".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InternalServerErrorAllOf - value: {} is invalid {}", + format!("Invalid header value for NetworkConfigurationResponseVersion - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InternalServerErrorAllOf - {}", + format!("Unable to convert header value '{}' into NetworkConfigurationResponseVersion - {}", value, err)) } }, @@ -1222,56 +1089,48 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// The name of the network. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidHexError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "invalid_hex")] - pub invalid_hex: String, +pub struct NetworkIdentifier { + #[serde(rename = "network")] + pub network: String, } -impl InvalidHexError { - pub fn new(type_: String, invalid_hex: String, ) -> InvalidHexError { - InvalidHexError { - type_: type_, - invalid_hex: invalid_hex, +impl NetworkIdentifier { + pub fn new(network: String, ) -> NetworkIdentifier { + NetworkIdentifier { + network: network, } } } -/// Converts the InvalidHexError value to the Query Parameters representation (style=form, explode=false) +/// Converts the NetworkIdentifier value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InvalidHexError { +impl std::string::ToString for NetworkIdentifier { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("invalid_hex".to_string()); - params.push(self.invalid_hex.to_string()); + params.push("network".to_string()); + params.push(self.network.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidHexError value +/// Converts Query Parameters representation (style=form, explode=false) to a NetworkIdentifier value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidHexError { +impl std::str::FromStr for NetworkIdentifier { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub invalid_hex: Vec, + pub network: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1283,14 +1142,13 @@ impl std::str::FromStr for InvalidHexError { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidHexError".to_string()) + None => return std::result::Result::Err("Missing value while parsing NetworkIdentifier".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "invalid_hex" => intermediate_rep.invalid_hex.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidHexError".to_string()) + "network" => intermediate_rep.network.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NetworkIdentifier".to_string()) } } @@ -1299,41 +1157,40 @@ impl std::str::FromStr for InvalidHexError { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidHexError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InvalidHexError".to_string())?, - invalid_hex: intermediate_rep.invalid_hex.into_iter().next().ok_or("invalid_hex missing in InvalidHexError".to_string())?, + std::result::Result::Ok(NetworkIdentifier { + network: intermediate_rep.network.into_iter().next().ok_or("network missing in NetworkIdentifier".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidHexError - value: {} is invalid {}", + format!("Invalid header value for NetworkIdentifier - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidHexError - {}", + format!("Unable to convert header value '{}' into NetworkIdentifier - {}", value, err)) } }, @@ -1347,45 +1204,61 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidHexErrorAllOf { - #[serde(rename = "invalid_hex")] - pub invalid_hex: String, +pub struct NotarizedTransaction { + #[serde(rename = "hash")] + pub hash: String, + + #[serde(rename = "signed_intent")] + pub signed_intent: models::SignedTransactionIntent, + + #[serde(rename = "notary_signature")] + pub notary_signature: String, } -impl InvalidHexErrorAllOf { - pub fn new(invalid_hex: String, ) -> InvalidHexErrorAllOf { - InvalidHexErrorAllOf { - invalid_hex: invalid_hex, +impl NotarizedTransaction { + pub fn new(hash: String, signed_intent: models::SignedTransactionIntent, notary_signature: String, ) -> NotarizedTransaction { + NotarizedTransaction { + hash: hash, + signed_intent: signed_intent, + notary_signature: notary_signature, } } } -/// Converts the InvalidHexErrorAllOf value to the Query Parameters representation (style=form, explode=false) +/// Converts the NotarizedTransaction value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InvalidHexErrorAllOf { +impl std::string::ToString for NotarizedTransaction { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("invalid_hex".to_string()); - params.push(self.invalid_hex.to_string()); + params.push("hash".to_string()); + params.push(self.hash.to_string()); + + // Skipping signed_intent in query parameter serialization + + + params.push("notary_signature".to_string()); + params.push(self.notary_signature.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidHexErrorAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a NotarizedTransaction value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidHexErrorAllOf { +impl std::str::FromStr for NotarizedTransaction { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub invalid_hex: Vec, + pub hash: Vec, + pub signed_intent: Vec, + pub notary_signature: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1397,13 +1270,15 @@ impl std::str::FromStr for InvalidHexErrorAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidHexErrorAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing NotarizedTransaction".to_string()) }; if let Some(key) = key_result { match key { - "invalid_hex" => intermediate_rep.invalid_hex.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidHexErrorAllOf".to_string()) + "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), + "signed_intent" => intermediate_rep.signed_intent.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notary_signature" => intermediate_rep.notary_signature.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NotarizedTransaction".to_string()) } } @@ -1412,1478 +1287,39 @@ impl std::str::FromStr for InvalidHexErrorAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidHexErrorAllOf { - invalid_hex: intermediate_rep.invalid_hex.into_iter().next().ok_or("invalid_hex missing in InvalidHexErrorAllOf".to_string())?, + std::result::Result::Ok(NotarizedTransaction { + hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in NotarizedTransaction".to_string())?, + signed_intent: intermediate_rep.signed_intent.into_iter().next().ok_or("signed_intent missing in NotarizedTransaction".to_string())?, + notary_signature: intermediate_rep.notary_signature.into_iter().next().ok_or("notary_signature missing in NotarizedTransaction".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidHexErrorAllOf - value: {} is invalid {}", + format!("Invalid header value for NotarizedTransaction - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidHexErrorAllOf - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidJsonError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, - -} - -impl InvalidJsonError { - pub fn new(type_: String, ) -> InvalidJsonError { - InvalidJsonError { - type_: type_, - cause: None, - } - } -} - -/// Converts the InvalidJsonError value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for InvalidJsonError { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidJsonError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidJsonError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub cause: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidJsonError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidJsonError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidJsonError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InvalidJsonError".to_string())?, - cause: intermediate_rep.cause.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidJsonError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidJsonError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidJsonErrorAllOf { - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, - -} - -impl InvalidJsonErrorAllOf { - pub fn new() -> InvalidJsonErrorAllOf { - InvalidJsonErrorAllOf { - cause: None, - } - } -} - -/// Converts the InvalidJsonErrorAllOf value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for InvalidJsonErrorAllOf { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidJsonErrorAllOf value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidJsonErrorAllOf { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub cause: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidJsonErrorAllOf".to_string()) - }; - - if let Some(key) = key_result { - match key { - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidJsonErrorAllOf".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidJsonErrorAllOf { - cause: intermediate_rep.cause.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidJsonErrorAllOf - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidJsonErrorAllOf - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidTransactionError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "message")] - pub message: String, - -} - -impl InvalidTransactionError { - pub fn new(type_: String, message: String, ) -> InvalidTransactionError { - InvalidTransactionError { - type_: type_, - message: message, - } - } -} - -/// Converts the InvalidTransactionError value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for InvalidTransactionError { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("message".to_string()); - params.push(self.message.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidTransactionError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidTransactionError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub message: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidTransactionError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidTransactionError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidTransactionError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InvalidTransactionError".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in InvalidTransactionError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidTransactionError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidTransactionError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidTransactionErrorAllOf { - #[serde(rename = "message")] - pub message: String, - -} - -impl InvalidTransactionErrorAllOf { - pub fn new(message: String, ) -> InvalidTransactionErrorAllOf { - InvalidTransactionErrorAllOf { - message: message, - } - } -} - -/// Converts the InvalidTransactionErrorAllOf value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for InvalidTransactionErrorAllOf { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("message".to_string()); - params.push(self.message.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidTransactionErrorAllOf value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidTransactionErrorAllOf { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub message: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidTransactionErrorAllOf".to_string()) - }; - - if let Some(key) = key_result { - match key { - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidTransactionErrorAllOf".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidTransactionErrorAllOf { - message: intermediate_rep.message.into_iter().next().ok_or("message missing in InvalidTransactionErrorAllOf".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidTransactionErrorAllOf - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidTransactionErrorAllOf - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct MempoolFullError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "mempool_transaction_count")] - pub mempool_transaction_count: i64, - -} - -impl MempoolFullError { - pub fn new(type_: String, mempool_transaction_count: i64, ) -> MempoolFullError { - MempoolFullError { - type_: type_, - mempool_transaction_count: mempool_transaction_count, - } - } -} - -/// Converts the MempoolFullError value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for MempoolFullError { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("mempool_transaction_count".to_string()); - params.push(self.mempool_transaction_count.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a MempoolFullError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for MempoolFullError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub mempool_transaction_count: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing MempoolFullError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "mempool_transaction_count" => intermediate_rep.mempool_transaction_count.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing MempoolFullError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(MempoolFullError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in MempoolFullError".to_string())?, - mempool_transaction_count: intermediate_rep.mempool_transaction_count.into_iter().next().ok_or("mempool_transaction_count missing in MempoolFullError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for MempoolFullError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into MempoolFullError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct MempoolFullErrorAllOf { - #[serde(rename = "mempool_transaction_count")] - pub mempool_transaction_count: i64, - -} - -impl MempoolFullErrorAllOf { - pub fn new(mempool_transaction_count: i64, ) -> MempoolFullErrorAllOf { - MempoolFullErrorAllOf { - mempool_transaction_count: mempool_transaction_count, - } - } -} - -/// Converts the MempoolFullErrorAllOf value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for MempoolFullErrorAllOf { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("mempool_transaction_count".to_string()); - params.push(self.mempool_transaction_count.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a MempoolFullErrorAllOf value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for MempoolFullErrorAllOf { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub mempool_transaction_count: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing MempoolFullErrorAllOf".to_string()) - }; - - if let Some(key) = key_result { - match key { - "mempool_transaction_count" => intermediate_rep.mempool_transaction_count.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing MempoolFullErrorAllOf".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(MempoolFullErrorAllOf { - mempool_transaction_count: intermediate_rep.mempool_transaction_count.into_iter().next().ok_or("mempool_transaction_count missing in MempoolFullErrorAllOf".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for MempoolFullErrorAllOf - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into MempoolFullErrorAllOf - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkConfigurationResponse { - #[serde(rename = "version")] - pub version: models::NetworkConfigurationResponseVersion, - - #[serde(rename = "network_identifier")] - pub network_identifier: models::NetworkIdentifier, - - /// The network suffix used for bech32 hrps used for addressing. - #[serde(rename = "network_hrp_suffix")] - pub network_hrp_suffix: String, - -} - -impl NetworkConfigurationResponse { - pub fn new(version: models::NetworkConfigurationResponseVersion, network_identifier: models::NetworkIdentifier, network_hrp_suffix: String, ) -> NetworkConfigurationResponse { - NetworkConfigurationResponse { - version: version, - network_identifier: network_identifier, - network_hrp_suffix: network_hrp_suffix, - } - } -} - -/// Converts the NetworkConfigurationResponse value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkConfigurationResponse { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping version in query parameter serialization - - // Skipping network_identifier in query parameter serialization - - - params.push("network_hrp_suffix".to_string()); - params.push(self.network_hrp_suffix.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponse value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkConfigurationResponse { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub version: Vec, - pub network_identifier: Vec, - pub network_hrp_suffix: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponse".to_string()) - }; - - if let Some(key) = key_result { - match key { - "version" => intermediate_rep.version.push(::from_str(val).map_err(|x| format!("{}", x))?), - "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), - "network_hrp_suffix" => intermediate_rep.network_hrp_suffix.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponse".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkConfigurationResponse { - version: intermediate_rep.version.into_iter().next().ok_or("version missing in NetworkConfigurationResponse".to_string())?, - network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in NetworkConfigurationResponse".to_string())?, - network_hrp_suffix: intermediate_rep.network_hrp_suffix.into_iter().next().ok_or("network_hrp_suffix missing in NetworkConfigurationResponse".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkConfigurationResponse - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkConfigurationResponse - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -/// Different versions regarding the node, network and api. -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkConfigurationResponseVersion { - #[serde(rename = "core_version")] - pub core_version: String, - - #[serde(rename = "api_version")] - pub api_version: String, - -} - -impl NetworkConfigurationResponseVersion { - pub fn new(core_version: String, api_version: String, ) -> NetworkConfigurationResponseVersion { - NetworkConfigurationResponseVersion { - core_version: core_version, - api_version: api_version, - } - } -} - -/// Converts the NetworkConfigurationResponseVersion value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkConfigurationResponseVersion { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("core_version".to_string()); - params.push(self.core_version.to_string()); - - - params.push("api_version".to_string()); - params.push(self.api_version.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponseVersion value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkConfigurationResponseVersion { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub core_version: Vec, - pub api_version: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponseVersion".to_string()) - }; - - if let Some(key) = key_result { - match key { - "core_version" => intermediate_rep.core_version.push(::from_str(val).map_err(|x| format!("{}", x))?), - "api_version" => intermediate_rep.api_version.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponseVersion".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkConfigurationResponseVersion { - core_version: intermediate_rep.core_version.into_iter().next().ok_or("core_version missing in NetworkConfigurationResponseVersion".to_string())?, - api_version: intermediate_rep.api_version.into_iter().next().ok_or("api_version missing in NetworkConfigurationResponseVersion".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkConfigurationResponseVersion - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkConfigurationResponseVersion - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkIdentifier { - #[serde(rename = "network")] - pub network: String, - -} - -impl NetworkIdentifier { - pub fn new(network: String, ) -> NetworkIdentifier { - NetworkIdentifier { - network: network, - } - } -} - -/// Converts the NetworkIdentifier value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkIdentifier { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("network".to_string()); - params.push(self.network.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkIdentifier value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkIdentifier { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub network: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkIdentifier".to_string()) - }; - - if let Some(key) = key_result { - match key { - "network" => intermediate_rep.network.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkIdentifier".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkIdentifier { - network: intermediate_rep.network.into_iter().next().ok_or("network missing in NetworkIdentifier".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkIdentifier - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkIdentifier - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkNotSupportedError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "supported_networks")] - pub supported_networks: Vec, - -} - -impl NetworkNotSupportedError { - pub fn new(type_: String, supported_networks: Vec, ) -> NetworkNotSupportedError { - NetworkNotSupportedError { - type_: type_, - supported_networks: supported_networks, - } - } -} - -/// Converts the NetworkNotSupportedError value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkNotSupportedError { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - // Skipping supported_networks in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkNotSupportedError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkNotSupportedError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub supported_networks: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkNotSupportedError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "supported_networks" => return std::result::Result::Err("Parsing a container in this style is not supported in NetworkNotSupportedError".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkNotSupportedError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkNotSupportedError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in NetworkNotSupportedError".to_string())?, - supported_networks: intermediate_rep.supported_networks.into_iter().next().ok_or("supported_networks missing in NetworkNotSupportedError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkNotSupportedError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkNotSupportedError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkNotSupportedErrorAllOf { - #[serde(rename = "supported_networks")] - pub supported_networks: Vec, - -} - -impl NetworkNotSupportedErrorAllOf { - pub fn new(supported_networks: Vec, ) -> NetworkNotSupportedErrorAllOf { - NetworkNotSupportedErrorAllOf { - supported_networks: supported_networks, - } - } -} - -/// Converts the NetworkNotSupportedErrorAllOf value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkNotSupportedErrorAllOf { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping supported_networks in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkNotSupportedErrorAllOf value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkNotSupportedErrorAllOf { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub supported_networks: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkNotSupportedErrorAllOf".to_string()) - }; - - if let Some(key) = key_result { - match key { - "supported_networks" => return std::result::Result::Err("Parsing a container in this style is not supported in NetworkNotSupportedErrorAllOf".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkNotSupportedErrorAllOf".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkNotSupportedErrorAllOf { - supported_networks: intermediate_rep.supported_networks.into_iter().next().ok_or("supported_networks missing in NetworkNotSupportedErrorAllOf".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkNotSupportedErrorAllOf - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkNotSupportedErrorAllOf - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NotarizedTransaction { - #[serde(rename = "hash")] - pub hash: String, - - #[serde(rename = "signed_intent")] - pub signed_intent: models::SignedTransactionIntent, - - #[serde(rename = "notary_signature")] - pub notary_signature: String, - -} - -impl NotarizedTransaction { - pub fn new(hash: String, signed_intent: models::SignedTransactionIntent, notary_signature: String, ) -> NotarizedTransaction { - NotarizedTransaction { - hash: hash, - signed_intent: signed_intent, - notary_signature: notary_signature, - } - } -} - -/// Converts the NotarizedTransaction value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NotarizedTransaction { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("hash".to_string()); - params.push(self.hash.to_string()); - - // Skipping signed_intent in query parameter serialization - - - params.push("notary_signature".to_string()); - params.push(self.notary_signature.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NotarizedTransaction value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NotarizedTransaction { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub hash: Vec, - pub signed_intent: Vec, - pub notary_signature: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NotarizedTransaction".to_string()) - }; - - if let Some(key) = key_result { - match key { - "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), - "signed_intent" => intermediate_rep.signed_intent.push(::from_str(val).map_err(|x| format!("{}", x))?), - "notary_signature" => intermediate_rep.notary_signature.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing NotarizedTransaction".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NotarizedTransaction { - hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in NotarizedTransaction".to_string())?, - signed_intent: intermediate_rep.signed_intent.into_iter().next().ok_or("signed_intent missing in NotarizedTransaction".to_string())?, - notary_signature: intermediate_rep.notary_signature.into_iter().next().ok_or("notary_signature missing in NotarizedTransaction".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NotarizedTransaction - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( format!("Unable to convert header value '{}' into NotarizedTransaction - {}", @@ -2898,129 +1334,6 @@ impl std::convert::TryFrom for header::IntoHeaderVal } -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct PreviewError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "message")] - pub message: String, - -} - -impl PreviewError { - pub fn new(type_: String, message: String, ) -> PreviewError { - PreviewError { - type_: type_, - message: message, - } - } -} - -/// Converts the PreviewError value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for PreviewError { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("message".to_string()); - params.push(self.message.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a PreviewError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for PreviewError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub message: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing PreviewError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing PreviewError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(PreviewError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in PreviewError".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in PreviewError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for PreviewError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into PreviewError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct SignedTransactionIntent { @@ -3799,12 +2112,16 @@ pub struct TransactionPreviewResponse { pub new_resource_addresses: Vec, #[serde(rename = "output")] + #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] + #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub output: Option>, + pub output: Option>>, #[serde(rename = "error_message")] + #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] + #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub error_message: Option, + pub error_message: Option>, } @@ -3850,13 +2167,13 @@ impl std::string::ToString for TransactionPreviewResponse { if let Some(ref output) = self.output { params.push("output".to_string()); - params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + params.push(output.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",").to_string())); } if let Some(ref error_message) = self.error_message { params.push("error_message".to_string()); - params.push(error_message.to_string()); + params.push(error_message.as_ref().map_or("null".to_string(), |x| x.to_string())); } params.join(",").to_string() @@ -3904,7 +2221,7 @@ impl std::str::FromStr for TransactionPreviewResponse { "new_component_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), "new_resource_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), + "error_message" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in TransactionPreviewResponse".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponse".to_string()) } } @@ -3921,8 +2238,8 @@ impl std::str::FromStr for TransactionPreviewResponse { new_package_addresses: intermediate_rep.new_package_addresses.into_iter().next().ok_or("new_package_addresses missing in TransactionPreviewResponse".to_string())?, new_component_addresses: intermediate_rep.new_component_addresses.into_iter().next().ok_or("new_component_addresses missing in TransactionPreviewResponse".to_string())?, new_resource_addresses: intermediate_rep.new_resource_addresses.into_iter().next().ok_or("new_resource_addresses missing in TransactionPreviewResponse".to_string())?, - output: intermediate_rep.output.into_iter().next(), - error_message: intermediate_rep.error_message.into_iter().next(), + output: std::result::Result::Err("Nullable types not supported in TransactionPreviewResponse".to_string())?, + error_message: std::result::Result::Err("Nullable types not supported in TransactionPreviewResponse".to_string())?, }) } } @@ -4099,12 +2416,16 @@ pub struct TransactionReceipt { pub fee_summary: models::FeeSummary, #[serde(rename = "output")] + #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] + #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub output: Option>, + pub output: Option>>, #[serde(rename = "error_message")] + #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] + #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub error_message: Option, + pub error_message: Option>, } @@ -4132,13 +2453,13 @@ impl std::string::ToString for TransactionReceipt { if let Some(ref output) = self.output { params.push("output".to_string()); - params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + params.push(output.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",").to_string())); } if let Some(ref error_message) = self.error_message { params.push("error_message".to_string()); - params.push(error_message.to_string()); + params.push(error_message.as_ref().map_or("null".to_string(), |x| x.to_string())); } params.join(",").to_string() @@ -4178,7 +2499,7 @@ impl std::str::FromStr for TransactionReceipt { "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| format!("{}", x))?), "fee_summary" => intermediate_rep.fee_summary.push(::from_str(val).map_err(|x| format!("{}", x))?), "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionReceipt".to_string()), - "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), + "error_message" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in TransactionReceipt".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing TransactionReceipt".to_string()) } } @@ -4191,8 +2512,8 @@ impl std::str::FromStr for TransactionReceipt { std::result::Result::Ok(TransactionReceipt { status: intermediate_rep.status.into_iter().next().ok_or("status missing in TransactionReceipt".to_string())?, fee_summary: intermediate_rep.fee_summary.into_iter().next().ok_or("fee_summary missing in TransactionReceipt".to_string())?, - output: intermediate_rep.output.into_iter().next(), - error_message: intermediate_rep.error_message.into_iter().next(), + output: std::result::Result::Err("Nullable types not supported in TransactionReceipt".to_string())?, + error_message: std::result::Result::Err("Nullable types not supported in TransactionReceipt".to_string())?, }) } } diff --git a/state-manager/core-api-server/src/core_api/mod.rs b/state-manager/core-api-server/src/core_api/mod.rs index c50fc6f9fb..5d02ef3d76 100644 --- a/state-manager/core-api-server/src/core_api/mod.rs +++ b/state-manager/core-api-server/src/core_api/mod.rs @@ -62,6 +62,7 @@ * permissions under this License. */ +mod errors; mod network_configuration; mod preview; pub mod server; diff --git a/state-manager/core-api-server/src/core_api/network_configuration.rs b/state-manager/core-api-server/src/core_api/network_configuration.rs index 453b96f849..6f98091386 100644 --- a/state-manager/core-api-server/src/core_api/network_configuration.rs +++ b/state-manager/core-api-server/src/core_api/network_configuration.rs @@ -1,23 +1,32 @@ +use crate::core_api::errors::{common_server_errors, RequestHandlingError}; use crate::core_api::generated::models::*; use crate::core_api::generated::{StatusNetworkConfigurationPostResponse, API_VERSION}; use state_manager::jni::state_manager::ActualStateManager; use std::sync::{Arc, Mutex}; -use swagger::ApiError; pub(crate) fn handle_network_configuration( state_manager: Arc>, -) -> Result { - handle_network_configuration_internal(state_manager) - .map(StatusNetworkConfigurationPostResponse::NetworkConfiguration) - .or_else(Ok) +) -> StatusNetworkConfigurationPostResponse { + match handle_network_configuration_internal(state_manager) { + Ok(response) => StatusNetworkConfigurationPostResponse::NetworkConfiguration(response), + Err(RequestHandlingError::ServerError(error_response)) => { + StatusNetworkConfigurationPostResponse::ServerError(error_response) + } + Err(RequestHandlingError::ClientError(error_response)) => + // No client errors are expected; returning a server error + { + StatusNetworkConfigurationPostResponse::ServerError(error_response) + } + } } fn handle_network_configuration_internal( state_manager: Arc>, -) -> Result { +) -> Result { let locked_state_manager = state_manager .lock() - .map_err(|_| server_error("Internal server error (state manager lock)"))?; + .map_err(|_| common_server_errors::state_manager_lock_error())?; + let network = locked_state_manager.network.clone(); Ok(NetworkConfigurationResponse { @@ -31,10 +40,3 @@ fn handle_network_configuration_internal( network_hrp_suffix: network.hrp_suffix, }) } - -fn server_error(message: &str) -> StatusNetworkConfigurationPostResponse { - StatusNetworkConfigurationPostResponse::ServerError(ErrorResponse::new( - 500, - message.to_string(), - )) -} diff --git a/state-manager/core-api-server/src/core_api/preview.rs b/state-manager/core-api-server/src/core_api/preview.rs index 588e935cf5..c5928bebd9 100644 --- a/state-manager/core-api-server/src/core_api/preview.rs +++ b/state-manager/core-api-server/src/core_api/preview.rs @@ -1,3 +1,4 @@ +use crate::core_api::errors::{common_server_errors, RequestHandlingError}; use crate::core_api::generated::models::*; use crate::core_api::generated::TransactionPreviewPostResponse; use radix_engine::transaction::{PreviewResult, TransactionOutcome, TransactionResult}; @@ -7,31 +8,37 @@ use scrypto::prelude::scrypto_decode; use state_manager::jni::state_manager::ActualStateManager; use state_manager::PreviewRequest; use std::sync::{Arc, Mutex}; -use swagger::ApiError; +use swagger::Nullable; use transaction::model::{PreviewFlags, TransactionManifest}; pub(crate) fn handle_preview( state_manager: Arc>, request: TransactionPreviewRequest, -) -> Result { - handle_preview_internal(state_manager, request) - .map(TransactionPreviewPostResponse::TransactionPreviewResponse) - .or_else(Ok) +) -> TransactionPreviewPostResponse { + match handle_preview_internal(state_manager, request) { + Ok(response) => TransactionPreviewPostResponse::TransactionPreviewResponse(response), + Err(RequestHandlingError::ClientError(error_response)) => { + TransactionPreviewPostResponse::ClientError(error_response) + } + Err(RequestHandlingError::ServerError(error_response)) => { + TransactionPreviewPostResponse::ServerError(error_response) + } + } } fn handle_preview_internal( state_manager: Arc>, request: TransactionPreviewRequest, -) -> Result { +) -> Result { let preview_request = parse_preview_request(request)?; let mut locked_state_manager = state_manager .lock() - .map_err(|_| server_error("Internal server error (state manager lock)"))?; + .map_err(|_| common_server_errors::state_manager_lock_error())?; let result = locked_state_manager .preview(preview_request) - .map_err(|e| client_error(&format!("{:?}", e)))?; + .map_err(preview_errors::engine_error)?; let bech32_encoder = Bech32Encoder::new(&locked_state_manager.network); @@ -40,40 +47,39 @@ fn handle_preview_internal( fn parse_preview_request( request: TransactionPreviewRequest, -) -> Result { +) -> Result { let cost_unit_limit: u32 = request .cost_unit_limit .parse() - .map_err(|_| client_error("Invalid cost_unit_limit"))?; + .map_err(|_| preview_errors::invalid_int_field("cost_unit_limit"))?; let tip_percentage: u32 = request .tip_percentage .parse() - .map_err(|_| client_error("Invalid tip_percentage"))?; + .map_err(|_| preview_errors::invalid_int_field("tip_percentage"))?; let nonce: u64 = request .nonce .parse() - .map_err(|_| client_error("Invalid nonce"))?; + .map_err(|_| preview_errors::invalid_int_field("nonce"))?; let manifest = hex::decode(request.manifest) .map(|manifest_bytes| { scrypto_decode::(&manifest_bytes) - .map_err(|_| client_error("Invalid manifest")) + .map_err(|_| preview_errors::invalid_manifest()) }) - .map_err(|_| client_error("Invalid manifest (malformed hex)"))??; + .map_err(|_| preview_errors::invalid_manifest())??; let signer_public_keys: Vec = request .signer_public_keys .into_iter() .flat_map(|s| { - hex::decode(s).map(|pub_key_bytes| { + hex::decode(s.clone()).map(|pub_key_bytes| { EcdsaPublicKey::try_from(&pub_key_bytes[..]) - .map_err(|_| client_error("Invalid signer public key")) - .map_err(|_| client_error("Invalid signer public key (malformed hex)")) + .map_err(|_| preview_errors::invalid_signer_pub_key(&s)) }) }) - .collect::, TransactionPreviewPostResponse>>()?; + .collect::, RequestHandlingError>>()?; Ok(PreviewRequest { manifest, @@ -90,7 +96,7 @@ fn parse_preview_request( fn to_api_response( result: PreviewResult, bech32_encoder: Bech32Encoder, -) -> Result { +) -> Result { let execution = result.receipt.execution; let fee_summary = execution.fee_summary; @@ -139,12 +145,16 @@ fn to_api_response( let (status, output, error_message) = match commit_result.outcome { TransactionOutcome::Success(output) => { let output_hex = output.into_iter().map(hex::encode).collect(); - (TransactionStatus::SUCCEEDED, Some(output_hex), None) + ( + TransactionStatus::SUCCEEDED, + Some(Nullable::Present(output_hex)), + None, + ) } TransactionOutcome::Failure(error) => ( TransactionStatus::FAILED, None, - Some(format!("{:?}", error)), + Some(Nullable::Present(format!("{:?}", error))), ), }; @@ -167,17 +177,30 @@ fn to_api_response( new_component_addresses: vec![], new_resource_addresses: vec![], output: None, - error_message: Some(format!("{:?}", reject_result)), + error_message: Some(Nullable::Present(format!("{:?}", reject_result))), }, }; Ok(response) } -fn client_error(message: &str) -> TransactionPreviewPostResponse { - TransactionPreviewPostResponse::ClientError(ErrorResponse::new(400, message.to_string())) -} +mod preview_errors { + use crate::core_api::errors::{client_error, RequestHandlingError}; + use radix_engine::transaction::PreviewError; + + pub(crate) fn engine_error(err: PreviewError) -> RequestHandlingError { + client_error(1, &format!("Engine error: {:?}", err)) + } + + pub(crate) fn invalid_int_field(field: &str) -> RequestHandlingError { + client_error(2, &format!("Invalid integer: {}", field)) + } + + pub(crate) fn invalid_manifest() -> RequestHandlingError { + client_error(3, "Invalid manifest") + } -fn server_error(message: &str) -> TransactionPreviewPostResponse { - TransactionPreviewPostResponse::ServerError(ErrorResponse::new(500, message.to_string())) + pub(crate) fn invalid_signer_pub_key(raw_key: &str) -> RequestHandlingError { + client_error(4, &format!("Invalid signer public key: {}", raw_key)) + } } diff --git a/state-manager/core-api-server/src/core_api/server.rs b/state-manager/core-api-server/src/core_api/server.rs index d64cf35811..2ee5cd1f29 100644 --- a/state-manager/core-api-server/src/core_api/server.rs +++ b/state-manager/core-api-server/src/core_api/server.rs @@ -140,7 +140,9 @@ where &self, _context: &C, ) -> Result { - network_configuration::handle_network_configuration(self.state_manager.clone()) + Ok(network_configuration::handle_network_configuration( + self.state_manager.clone(), + )) } async fn transaction_preview_post( @@ -148,7 +150,7 @@ where request: models::TransactionPreviewRequest, _context: &C, ) -> Result { - preview::handle_preview(self.state_manager.clone(), request) + Ok(preview::handle_preview(self.state_manager.clone(), request)) } async fn transaction_submit_post( @@ -156,7 +158,10 @@ where request: models::TransactionSubmitRequest, _context: &C, ) -> Result { - transactions::handle_submit_transaction(self.state_manager.clone(), request) + Ok(transactions::handle_submit_transaction( + self.state_manager.clone(), + request, + )) } async fn transactions_post( @@ -164,7 +169,10 @@ where request: CommittedTransactionsRequest, _context: &C, ) -> Result { - transactions::handle_transactions(self.state_manager.clone(), request) + Ok(transactions::handle_get_committed_transactions( + self.state_manager.clone(), + request, + )) } } diff --git a/state-manager/core-api-server/src/core_api/transactions.rs b/state-manager/core-api-server/src/core_api/transactions.rs index b85ca7bb18..d8e25bcf37 100644 --- a/state-manager/core-api-server/src/core_api/transactions.rs +++ b/state-manager/core-api-server/src/core_api/transactions.rs @@ -1,3 +1,4 @@ +use crate::core_api::errors::{common_server_errors, RequestHandlingError}; use crate::core_api::generated::models::*; use crate::core_api::generated::{TransactionSubmitPostResponse, TransactionsPostResponse}; use scrypto::buffer::scrypto_decode; @@ -8,24 +9,30 @@ use state_manager::mempool::Mempool; use state_manager::{MempoolError, TId, TemporaryTransactionReceipt, Transaction}; use std::cmp; use std::sync::{Arc, Mutex}; -use swagger::ApiError; +use swagger::Nullable; use transaction::model::NotarizedTransaction as EngineNotarizedTransaction; pub(crate) fn handle_submit_transaction( state_manager: Arc>, request: TransactionSubmitRequest, -) -> Result { - handle_submit_transaction_internal(state_manager, request) - .map(TransactionSubmitPostResponse::TransactionSubmitResponse) - .or_else(Ok) +) -> TransactionSubmitPostResponse { + match handle_submit_transaction_internal(state_manager, request) { + Ok(response) => TransactionSubmitPostResponse::TransactionSubmitResponse(response), + Err(RequestHandlingError::ClientError(error_response)) => { + TransactionSubmitPostResponse::ClientError(error_response) + } + Err(RequestHandlingError::ServerError(error_response)) => { + TransactionSubmitPostResponse::ServerError(error_response) + } + } } fn handle_submit_transaction_internal( state_manager: Arc>, request: TransactionSubmitRequest, -) -> Result { +) -> Result { let transaction_bytes = hex::decode(request.notarized_transaction) - .map_err(|_| submit_client_error("Invalid transaction (malformed hex)"))?; + .map_err(|_| transaction_errors::invalid_transaction())?; let tid = sha256_twice(transaction_bytes.clone()); @@ -38,7 +45,7 @@ fn handle_submit_transaction_internal( let mut locked_state_manager = state_manager .lock() - .map_err(|_| submit_server_error("Internal server error (state manager lock)"))?; + .map_err(|_| common_server_errors::state_manager_lock_error())?; let result = locked_state_manager.mempool.add_transaction(transaction); @@ -48,53 +55,50 @@ fn handle_submit_transaction_internal( Err(MempoolError::Full { current_size: _, max_size: _, - }) => Err(submit_server_error("Mempool is full")), - Err(MempoolError::TransactionValidationError(err)) => Err(submit_client_error(&format!( - "Transaction validation error: {:?}", - err - ))), + }) => Err(transaction_errors::mempool_is_full()), + Err(MempoolError::TransactionValidationError(err)) => { + Err(transaction_errors::transaction_validation_error(err)) + } } } -fn submit_client_error(message: &str) -> TransactionSubmitPostResponse { - TransactionSubmitPostResponse::ClientError(ErrorResponse::new(400, message.to_string())) -} - -fn submit_server_error(message: &str) -> TransactionSubmitPostResponse { - TransactionSubmitPostResponse::ServerError(ErrorResponse::new(500, message.to_string())) -} - -pub(crate) fn handle_transactions( +pub(crate) fn handle_get_committed_transactions( state_manager: Arc>, request: CommittedTransactionsRequest, -) -> Result { - handle_transactions_internal(state_manager, request) - .map(TransactionsPostResponse::CommittedTransactionsResponse) - .or_else(Ok) +) -> TransactionsPostResponse { + match handle_get_committed_transactions_internal(state_manager, request) { + Ok(response) => TransactionsPostResponse::CommittedTransactionsResponse(response), + Err(RequestHandlingError::ClientError(error_response)) => { + TransactionsPostResponse::ClientError(error_response) + } + Err(RequestHandlingError::ServerError(error_response)) => { + TransactionsPostResponse::ServerError(error_response) + } + } } -fn handle_transactions_internal( +fn handle_get_committed_transactions_internal( state_manager: Arc>, request: CommittedTransactionsRequest, -) -> Result { - let locked_state_manager = state_manager - .lock() - .map_err(|_| transactions_server_error("Internal server error (state manager lock)"))?; - +) -> Result { let initial_state_version: u64 = request .state_version .parse() - .map_err(|_| transactions_client_error("Invalid state_version"))?; + .map_err(|_| transaction_errors::invalid_int_field("state_version"))?; let limit: u64 = request .limit .try_into() - .map_err(|_| transactions_client_error("Invalid limit"))?; + .map_err(|_| transaction_errors::invalid_int_field("limit"))?; let state_version_at_limit: u64 = initial_state_version .checked_add(limit) .and_then(|v| v.checked_sub(1)) - .ok_or_else(|| transactions_client_error("Invalid limit"))?; + .ok_or_else(|| transaction_errors::invalid_int_field("limit"))?; + + let locked_state_manager = state_manager + .lock() + .map_err(|_| common_server_errors::state_manager_lock_error())?; let up_to_state_version_inclusive = cmp::min( state_version_at_limit, @@ -120,9 +124,9 @@ fn handle_transactions_internal( .map(|notarized_tx| { to_api_committed_transaction(notarized_tx, receipt.clone(), state_version) }) - .map_err(|_| transactions_server_error("Invalid committed txn payload")) + .map_err(|_| transaction_errors::invalid_committed_txn()) }) - .collect::, TransactionsPostResponse>>()?; + .collect::, RequestHandlingError>>()?; Ok(CommittedTransactionsResponse { state_version: request.state_version, @@ -186,16 +190,35 @@ fn to_api_committed_transaction( xrd_burned: "0".to_string(), xrd_tipped: "0".to_string(), }, - output: Some(vec!["00".to_string()]), // TODO: fixme (needs receipt) - error_message: None, // TODO: fixme (needs receipt) + output: Some(Nullable::Present(vec!["00".to_string()])), // TODO: fixme (needs receipt) + error_message: None, // TODO: fixme (needs receipt) }, } } -fn transactions_server_error(message: &str) -> TransactionsPostResponse { - TransactionsPostResponse::ServerError(ErrorResponse::new(500, message.to_string())) -} +mod transaction_errors { + use crate::core_api::errors::{client_error, server_error, RequestHandlingError}; + use transaction::errors::TransactionValidationError; -fn transactions_client_error(message: &str) -> TransactionsPostResponse { - TransactionsPostResponse::ClientError(ErrorResponse::new(400, message.to_string())) + pub(crate) fn invalid_transaction() -> RequestHandlingError { + client_error(1, "Invalid transaction payload") + } + + pub(crate) fn mempool_is_full() -> RequestHandlingError { + client_error(2, "Mempool is full") + } + + pub(crate) fn transaction_validation_error( + err: TransactionValidationError, + ) -> RequestHandlingError { + client_error(3, &format!("Transaction validation error: {:?}", err)) + } + + pub(crate) fn invalid_int_field(field: &str) -> RequestHandlingError { + client_error(4, &format!("Invalid integer: {}", field)) + } + + pub(crate) fn invalid_committed_txn() -> RequestHandlingError { + server_error(5, "Internal server error: invalid committed txn payload") + } } From 024e4a9570d495f13a3382da608206d531f023c5 Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Mon, 29 Aug 2022 16:53:06 +0200 Subject: [PATCH 4/7] Remove nullable in api specs --- state-manager/core-api-server/core-api-spec.yaml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/state-manager/core-api-server/core-api-spec.yaml b/state-manager/core-api-server/core-api-spec.yaml index 184b72cc5f..bbeb7b2d9b 100644 --- a/state-manager/core-api-server/core-api-spec.yaml +++ b/state-manager/core-api-server/core-api-spec.yaml @@ -162,12 +162,10 @@ components: "$ref": "#/components/schemas/FeeSummary" output: type: array - nullable: true items: type: string error_message: type: string - nullable: true NotarizedTransaction: type: object required: @@ -275,7 +273,6 @@ components: trace_id: description: A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. type: string - nullable: true ######################################### # GENERAL / SHARED MODELS - Transaction # ######################################### @@ -437,12 +434,10 @@ components: type: string output: type: array - nullable: true items: type: string error_message: type: string - nullable: true ########################## # REQUEST: /transactions # ########################## From 764a08427bff6677fc7960923c0a36db9ee743d1 Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Mon, 29 Aug 2022 18:38:15 +0200 Subject: [PATCH 5/7] Improve core api descriptions --- .../core-api-server/core-api-spec.yaml | 57 +++++-- .../src/core_api/generated/models.rs | 141 +++++++++++------- .../core-api-server/src/core_api/preview.rs | 7 +- .../src/core_api/transactions.rs | 3 +- 4 files changed, 133 insertions(+), 75 deletions(-) diff --git a/state-manager/core-api-server/core-api-spec.yaml b/state-manager/core-api-server/core-api-spec.yaml index bbeb7b2d9b..8fc80f7d6c 100644 --- a/state-manager/core-api-server/core-api-spec.yaml +++ b/state-manager/core-api-server/core-api-spec.yaml @@ -152,6 +152,7 @@ components: description: The status of the transaction TransactionReceipt: type: object + description: The transaction execution receipt required: - status - fee_summary @@ -164,8 +165,10 @@ components: type: array items: type: string + description: The engine return data (only present if status is succeeded) error_message: type: string + description: Error message (only present if status is failed or rejected) NotarizedTransaction: type: object required: @@ -175,10 +178,12 @@ components: properties: hash: type: string + description: The transaction hash, hex-encoded. signed_intent: "$ref": "#/components/schemas/SignedTransactionIntent" notary_signature: type: string + description: The notary signature, hex-encoded. SignedTransactionIntent: type: object required: @@ -188,6 +193,7 @@ components: properties: hash: type: string + description: Signed transaction intent hash, hex-encoded. intent: "$ref": "#/components/schemas/TransactionIntent" intent_signatures: @@ -202,8 +208,10 @@ components: properties: public_key: type: string + description: Signer public key, hex-encoded. signature: type: string + description: The signature, hex-encoded. TransactionIntent: type: object required: @@ -213,10 +221,12 @@ components: properties: hash: type: string + description: Transaction intent hash, hex-encoded. header: "$ref": "#/components/schemas/TransactionHeader" manifest: type: string + description: Transaction manifest, SBOR-encoded and then hex-encoded. TransactionHeader: type: object required: @@ -236,18 +246,25 @@ components: type: integer start_epoch_inclusive: type: string + description: A decimal 64-bit unsigned integer. end_epoch_exclusive: type: string + description: A decimal 64-bit unsigned integer. nonce: type: string + description: A decimal 64-bit unsigned integer. notary_public_key: type: string + description: A hex-encoded public key of a notary. notary_as_signatory: type: boolean + description: Specifies whether the notary's signature should be included in transaction signers list cost_unit_limit: type: string + description: Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. tip_percentage: type: string + description: Specifies the validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of "1" corresponds to 1%). NetworkIdentifier: description: The name of the network. type: object @@ -290,19 +307,26 @@ components: properties: loan_fully_repaid: type: boolean + description: Specifies whether the transaction execution loan has been fully repaid. cost_unit_limit: type: string + description: Maximum amount of cost units available for the transaction execution. A decimal 32-bit unsigned integer. cost_unit_consumed: type: string + description: The amount of cost units consumed by the transaction execution. A decimal 32-bit unsigned integer. cost_unit_price: type: string + description: The XRD price of a single cost unit. A fixed-scale 256-bit decimal number. tip_percentage: type: string + description: The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of "1" corresponds to 1%). xrd_burned: type: string + description: The total amount of XRD burned. A fixed-scale 256-bit decimal number. xrd_tipped: type: string -########################################## + description: The total amount of XRD tipped to validators. A fixed-scale 256-bit decimal number. + ########################################## # REQUEST: /status/network-configuration # ########################################## NetworkConfigurationResponse: @@ -371,19 +395,19 @@ components: description: A transaction manifest. Sbor encoded, and then hex encoded. type: string cost_unit_limit: - description: A limit of cost units available for execution type: string + description: Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. tip_percentage: - description: A tip for the validator type: string + description: The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of "1" corresponds to 1%). nonce: - description: A nonce value to use for execution type: string + description: The nonce value to use for execution. A decimal 64-bit unsigned integer. signer_public_keys: - description: A list of public keys to be used as transaction signers, in a compressed format, hex encoded. type: array items: type: string + description: A list of public keys to be used as transaction signers, in a compressed format, hex encoded. flags: type: object required: @@ -418,17 +442,17 @@ components: message: type: string new_package_addresses: - description: A list of new package addresses + description: A list of new package addresses, hex-encoded. type: array items: type: string new_component_addresses: - description: A list of new component addresses + description: A list of new component addresses, hex-encoded. type: array items: type: string new_resource_addresses: - description: A list of new resource addresses + description: A list of new resource addresses, hex-encoded. type: array items: type: string @@ -447,26 +471,32 @@ components: type: object required: - network_identifier - - state_version + - start_state_version - limit properties: network_identifier: "$ref": "#/components/schemas/NetworkIdentifier" - state_version: + start_state_version: type: string + description: A decimal 64-bit unsigned integer. limit: description: The maximum number of transactions that will be returned. type: integer CommittedTransactionsResponse: type: object required: - - state_version + - start_state_version + - max_state_version - transactions properties: - state_version: + start_state_version: + type: string + description: The first state version returned. A decimal 64-bit unsigned integer. + max_state_version: type: string + description: The maximum state version returned. A decimal 64-bit unsigned integer. transactions: - description: A committed transactions list starting from the `state_version`. + description: A committed transactions list starting from the `start_state_version_inclusive`. type: array items: "$ref": "#/components/schemas/CommittedTransaction" @@ -479,6 +509,7 @@ components: properties: state_version: type: string + description: The resultant state version after the txn has been committed. A decimal 64-bit unsigned integer. notarized_transaction: "$ref": "#/components/schemas/NotarizedTransaction" receipt: diff --git a/state-manager/core-api-server/src/core_api/generated/models.rs b/state-manager/core-api-server/src/core_api/generated/models.rs index af9a39bd10..9bb0d2bd19 100644 --- a/state-manager/core-api-server/src/core_api/generated/models.rs +++ b/state-manager/core-api-server/src/core_api/generated/models.rs @@ -7,6 +7,7 @@ use crate::core_api::generated::header; #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct CommittedTransaction { + /// The resultant state version after the txn has been committed. A decimal 64-bit unsigned integer. #[serde(rename = "state_version")] pub state_version: String, @@ -141,8 +142,9 @@ pub struct CommittedTransactionsRequest { #[serde(rename = "network_identifier")] pub network_identifier: models::NetworkIdentifier, - #[serde(rename = "state_version")] - pub state_version: String, + /// A decimal 64-bit unsigned integer. + #[serde(rename = "start_state_version")] + pub start_state_version: String, /// The maximum number of transactions that will be returned. #[serde(rename = "limit")] @@ -151,10 +153,10 @@ pub struct CommittedTransactionsRequest { } impl CommittedTransactionsRequest { - pub fn new(network_identifier: models::NetworkIdentifier, state_version: String, limit: isize, ) -> CommittedTransactionsRequest { + pub fn new(network_identifier: models::NetworkIdentifier, start_state_version: String, limit: isize, ) -> CommittedTransactionsRequest { CommittedTransactionsRequest { network_identifier: network_identifier, - state_version: state_version, + start_state_version: start_state_version, limit: limit, } } @@ -169,8 +171,8 @@ impl std::string::ToString for CommittedTransactionsRequest { // Skipping network_identifier in query parameter serialization - params.push("state_version".to_string()); - params.push(self.state_version.to_string()); + params.push("start_state_version".to_string()); + params.push(self.start_state_version.to_string()); params.push("limit".to_string()); @@ -191,7 +193,7 @@ impl std::str::FromStr for CommittedTransactionsRequest { // An intermediate representation of the struct to use for parsing. struct IntermediateRep { pub network_identifier: Vec, - pub state_version: Vec, + pub start_state_version: Vec, pub limit: Vec, } @@ -210,7 +212,7 @@ impl std::str::FromStr for CommittedTransactionsRequest { if let Some(key) = key_result { match key { "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), - "state_version" => intermediate_rep.state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "start_state_version" => intermediate_rep.start_state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), "limit" => intermediate_rep.limit.push(::from_str(val).map_err(|x| format!("{}", x))?), _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransactionsRequest".to_string()) } @@ -223,7 +225,7 @@ impl std::str::FromStr for CommittedTransactionsRequest { // Use the intermediate representation to return the struct std::result::Result::Ok(CommittedTransactionsRequest { network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in CommittedTransactionsRequest".to_string())?, - state_version: intermediate_rep.state_version.into_iter().next().ok_or("state_version missing in CommittedTransactionsRequest".to_string())?, + start_state_version: intermediate_rep.start_state_version.into_iter().next().ok_or("start_state_version missing in CommittedTransactionsRequest".to_string())?, limit: intermediate_rep.limit.into_iter().next().ok_or("limit missing in CommittedTransactionsRequest".to_string())?, }) } @@ -271,19 +273,25 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct CommittedTransactionsResponse { - #[serde(rename = "state_version")] - pub state_version: String, + /// The first state version returned. A decimal 64-bit unsigned integer. + #[serde(rename = "start_state_version")] + pub start_state_version: String, - /// A committed transactions list starting from the `state_version`. + /// The maximum state version returned. A decimal 64-bit unsigned integer. + #[serde(rename = "max_state_version")] + pub max_state_version: String, + + /// A committed transactions list starting from the `start_state_version_inclusive`. #[serde(rename = "transactions")] pub transactions: Vec, } impl CommittedTransactionsResponse { - pub fn new(state_version: String, transactions: Vec, ) -> CommittedTransactionsResponse { + pub fn new(start_state_version: String, max_state_version: String, transactions: Vec, ) -> CommittedTransactionsResponse { CommittedTransactionsResponse { - state_version: state_version, + start_state_version: start_state_version, + max_state_version: max_state_version, transactions: transactions, } } @@ -296,8 +304,12 @@ impl std::string::ToString for CommittedTransactionsResponse { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("state_version".to_string()); - params.push(self.state_version.to_string()); + params.push("start_state_version".to_string()); + params.push(self.start_state_version.to_string()); + + + params.push("max_state_version".to_string()); + params.push(self.max_state_version.to_string()); // Skipping transactions in query parameter serialization @@ -315,7 +327,8 @@ impl std::str::FromStr for CommittedTransactionsResponse { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub state_version: Vec, + pub start_state_version: Vec, + pub max_state_version: Vec, pub transactions: Vec>, } @@ -333,7 +346,8 @@ impl std::str::FromStr for CommittedTransactionsResponse { if let Some(key) = key_result { match key { - "state_version" => intermediate_rep.state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "start_state_version" => intermediate_rep.start_state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "max_state_version" => intermediate_rep.max_state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), "transactions" => return std::result::Result::Err("Parsing a container in this style is not supported in CommittedTransactionsResponse".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransactionsResponse".to_string()) } @@ -345,7 +359,8 @@ impl std::str::FromStr for CommittedTransactionsResponse { // Use the intermediate representation to return the struct std::result::Result::Ok(CommittedTransactionsResponse { - state_version: intermediate_rep.state_version.into_iter().next().ok_or("state_version missing in CommittedTransactionsResponse".to_string())?, + start_state_version: intermediate_rep.start_state_version.into_iter().next().ok_or("start_state_version missing in CommittedTransactionsResponse".to_string())?, + max_state_version: intermediate_rep.max_state_version.into_iter().next().ok_or("max_state_version missing in CommittedTransactionsResponse".to_string())?, transactions: intermediate_rep.transactions.into_iter().next().ok_or("transactions missing in CommittedTransactionsResponse".to_string())?, }) } @@ -403,10 +418,8 @@ pub struct ErrorResponse { /// A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. #[serde(rename = "trace_id")] - #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] - #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub trace_id: Option>, + pub trace_id: Option, } @@ -437,7 +450,7 @@ impl std::string::ToString for ErrorResponse { if let Some(ref trace_id) = self.trace_id { params.push("trace_id".to_string()); - params.push(trace_id.as_ref().map_or("null".to_string(), |x| x.to_string())); + params.push(trace_id.to_string()); } params.join(",").to_string() @@ -475,7 +488,7 @@ impl std::str::FromStr for ErrorResponse { match key { "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| format!("{}", x))?), "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - "trace_id" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ErrorResponse".to_string()), + "trace_id" => intermediate_rep.trace_id.push(::from_str(val).map_err(|x| format!("{}", x))?), _ => return std::result::Result::Err("Unexpected key while parsing ErrorResponse".to_string()) } } @@ -488,7 +501,7 @@ impl std::str::FromStr for ErrorResponse { std::result::Result::Ok(ErrorResponse { code: intermediate_rep.code.into_iter().next().ok_or("code missing in ErrorResponse".to_string())?, message: intermediate_rep.message.into_iter().next().ok_or("message missing in ErrorResponse".to_string())?, - trace_id: std::result::Result::Err("Nullable types not supported in ErrorResponse".to_string())?, + trace_id: intermediate_rep.trace_id.into_iter().next(), }) } } @@ -536,24 +549,31 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct FeeSummary { + /// Specifies whether the transaction execution loan has been fully repaid. #[serde(rename = "loan_fully_repaid")] pub loan_fully_repaid: bool, + /// Maximum amount of cost units available for the transaction execution. A decimal 32-bit unsigned integer. #[serde(rename = "cost_unit_limit")] pub cost_unit_limit: String, + /// The amount of cost units consumed by the transaction execution. A decimal 32-bit unsigned integer. #[serde(rename = "cost_unit_consumed")] pub cost_unit_consumed: String, + /// The XRD price of a single cost unit. A fixed-scale 256-bit decimal number. #[serde(rename = "cost_unit_price")] pub cost_unit_price: String, + /// The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of \"1\" corresponds to 1%). #[serde(rename = "tip_percentage")] pub tip_percentage: String, + /// The total amount of XRD burned. A fixed-scale 256-bit decimal number. #[serde(rename = "xrd_burned")] pub xrd_burned: String, + /// The total amount of XRD tipped to validators. A fixed-scale 256-bit decimal number. #[serde(rename = "xrd_tipped")] pub xrd_tipped: String, @@ -714,9 +734,11 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct IntentSignature { + /// Signer public key, hex-encoded. #[serde(rename = "public_key")] pub public_key: String, + /// The signature, hex-encoded. #[serde(rename = "signature")] pub signature: String, @@ -1205,12 +1227,14 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct NotarizedTransaction { + /// The transaction hash, hex-encoded. #[serde(rename = "hash")] pub hash: String, #[serde(rename = "signed_intent")] pub signed_intent: models::SignedTransactionIntent, + /// The notary signature, hex-encoded. #[serde(rename = "notary_signature")] pub notary_signature: String, @@ -1337,6 +1361,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct SignedTransactionIntent { + /// Signed transaction intent hash, hex-encoded. #[serde(rename = "hash")] pub hash: String, @@ -1473,24 +1498,31 @@ pub struct TransactionHeader { #[serde(rename = "network_id")] pub network_id: isize, + /// A decimal 64-bit unsigned integer. #[serde(rename = "start_epoch_inclusive")] pub start_epoch_inclusive: String, + /// A decimal 64-bit unsigned integer. #[serde(rename = "end_epoch_exclusive")] pub end_epoch_exclusive: String, + /// A decimal 64-bit unsigned integer. #[serde(rename = "nonce")] pub nonce: String, + /// A hex-encoded public key of a notary. #[serde(rename = "notary_public_key")] pub notary_public_key: String, + /// Specifies whether the notary's signature should be included in transaction signers list #[serde(rename = "notary_as_signatory")] pub notary_as_signatory: bool, + /// Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. #[serde(rename = "cost_unit_limit")] pub cost_unit_limit: String, + /// Specifies the validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of \"1\" corresponds to 1%). #[serde(rename = "tip_percentage")] pub tip_percentage: String, @@ -1667,12 +1699,14 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct TransactionIntent { + /// Transaction intent hash, hex-encoded. #[serde(rename = "hash")] pub hash: String, #[serde(rename = "header")] pub header: models::TransactionHeader, + /// Transaction manifest, SBOR-encoded and then hex-encoded. #[serde(rename = "manifest")] pub manifest: String, @@ -1806,15 +1840,15 @@ pub struct TransactionPreviewRequest { #[serde(rename = "manifest")] pub manifest: String, - /// A limit of cost units available for execution + /// Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. #[serde(rename = "cost_unit_limit")] pub cost_unit_limit: String, - /// A tip for the validator + /// The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of \"1\" corresponds to 1%). #[serde(rename = "tip_percentage")] pub tip_percentage: String, - /// A nonce value to use for execution + /// The nonce value to use for execution. A decimal 64-bit unsigned integer. #[serde(rename = "nonce")] pub nonce: String, @@ -2099,29 +2133,25 @@ pub struct TransactionPreviewResponse { #[serde(rename = "logs")] pub logs: Vec, - /// A list of new package addresses + /// A list of new package addresses, hex-encoded. #[serde(rename = "new_package_addresses")] pub new_package_addresses: Vec, - /// A list of new component addresses + /// A list of new component addresses, hex-encoded. #[serde(rename = "new_component_addresses")] pub new_component_addresses: Vec, - /// A list of new resource addresses + /// A list of new resource addresses, hex-encoded. #[serde(rename = "new_resource_addresses")] pub new_resource_addresses: Vec, #[serde(rename = "output")] - #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] - #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub output: Option>>, + pub output: Option>, #[serde(rename = "error_message")] - #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] - #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub error_message: Option>, + pub error_message: Option, } @@ -2167,13 +2197,13 @@ impl std::string::ToString for TransactionPreviewResponse { if let Some(ref output) = self.output { params.push("output".to_string()); - params.push(output.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",").to_string())); + params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); } if let Some(ref error_message) = self.error_message { params.push("error_message".to_string()); - params.push(error_message.as_ref().map_or("null".to_string(), |x| x.to_string())); + params.push(error_message.to_string()); } params.join(",").to_string() @@ -2221,7 +2251,7 @@ impl std::str::FromStr for TransactionPreviewResponse { "new_component_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), "new_resource_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "error_message" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in TransactionPreviewResponse".to_string()), + "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponse".to_string()) } } @@ -2238,8 +2268,8 @@ impl std::str::FromStr for TransactionPreviewResponse { new_package_addresses: intermediate_rep.new_package_addresses.into_iter().next().ok_or("new_package_addresses missing in TransactionPreviewResponse".to_string())?, new_component_addresses: intermediate_rep.new_component_addresses.into_iter().next().ok_or("new_component_addresses missing in TransactionPreviewResponse".to_string())?, new_resource_addresses: intermediate_rep.new_resource_addresses.into_iter().next().ok_or("new_resource_addresses missing in TransactionPreviewResponse".to_string())?, - output: std::result::Result::Err("Nullable types not supported in TransactionPreviewResponse".to_string())?, - error_message: std::result::Result::Err("Nullable types not supported in TransactionPreviewResponse".to_string())?, + output: intermediate_rep.output.into_iter().next(), + error_message: intermediate_rep.error_message.into_iter().next(), }) } } @@ -2406,6 +2436,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// The transaction execution receipt #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct TransactionReceipt { @@ -2415,17 +2446,15 @@ pub struct TransactionReceipt { #[serde(rename = "fee_summary")] pub fee_summary: models::FeeSummary, + /// The engine return data (only present if status is succeeded) #[serde(rename = "output")] - #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] - #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub output: Option>>, + pub output: Option>, + /// Error message (only present if status is failed or rejected) #[serde(rename = "error_message")] - #[serde(deserialize_with = "swagger::nullable_format::deserialize_optional_nullable")] - #[serde(default = "swagger::nullable_format::default_optional_nullable")] #[serde(skip_serializing_if="Option::is_none")] - pub error_message: Option>, + pub error_message: Option, } @@ -2453,13 +2482,13 @@ impl std::string::ToString for TransactionReceipt { if let Some(ref output) = self.output { params.push("output".to_string()); - params.push(output.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",").to_string())); + params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); } if let Some(ref error_message) = self.error_message { params.push("error_message".to_string()); - params.push(error_message.as_ref().map_or("null".to_string(), |x| x.to_string())); + params.push(error_message.to_string()); } params.join(",").to_string() @@ -2499,7 +2528,7 @@ impl std::str::FromStr for TransactionReceipt { "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| format!("{}", x))?), "fee_summary" => intermediate_rep.fee_summary.push(::from_str(val).map_err(|x| format!("{}", x))?), "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionReceipt".to_string()), - "error_message" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in TransactionReceipt".to_string()), + "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), _ => return std::result::Result::Err("Unexpected key while parsing TransactionReceipt".to_string()) } } @@ -2512,8 +2541,8 @@ impl std::str::FromStr for TransactionReceipt { std::result::Result::Ok(TransactionReceipt { status: intermediate_rep.status.into_iter().next().ok_or("status missing in TransactionReceipt".to_string())?, fee_summary: intermediate_rep.fee_summary.into_iter().next().ok_or("fee_summary missing in TransactionReceipt".to_string())?, - output: std::result::Result::Err("Nullable types not supported in TransactionReceipt".to_string())?, - error_message: std::result::Result::Err("Nullable types not supported in TransactionReceipt".to_string())?, + output: intermediate_rep.output.into_iter().next(), + error_message: intermediate_rep.error_message.into_iter().next(), }) } } @@ -2577,9 +2606,9 @@ pub enum TransactionStatus { impl std::fmt::Display for TransactionStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - TransactionStatus::SUCCEEDED => write!(f, "succeeded"), - TransactionStatus::FAILED => write!(f, "failed"), - TransactionStatus::REJECTED => write!(f, "rejected"), + TransactionStatus::SUCCEEDED => write!(f, "{}", "succeeded"), + TransactionStatus::FAILED => write!(f, "{}", "failed"), + TransactionStatus::REJECTED => write!(f, "{}", "rejected"), } } } diff --git a/state-manager/core-api-server/src/core_api/preview.rs b/state-manager/core-api-server/src/core_api/preview.rs index c5928bebd9..a4257de5dd 100644 --- a/state-manager/core-api-server/src/core_api/preview.rs +++ b/state-manager/core-api-server/src/core_api/preview.rs @@ -8,7 +8,6 @@ use scrypto::prelude::scrypto_decode; use state_manager::jni::state_manager::ActualStateManager; use state_manager::PreviewRequest; use std::sync::{Arc, Mutex}; -use swagger::Nullable; use transaction::model::{PreviewFlags, TransactionManifest}; pub(crate) fn handle_preview( @@ -147,14 +146,14 @@ fn to_api_response( let output_hex = output.into_iter().map(hex::encode).collect(); ( TransactionStatus::SUCCEEDED, - Some(Nullable::Present(output_hex)), + Some(output_hex), None, ) } TransactionOutcome::Failure(error) => ( TransactionStatus::FAILED, None, - Some(Nullable::Present(format!("{:?}", error))), + Some(format!("{:?}", error)), ), }; @@ -177,7 +176,7 @@ fn to_api_response( new_component_addresses: vec![], new_resource_addresses: vec![], output: None, - error_message: Some(Nullable::Present(format!("{:?}", reject_result))), + error_message: Some(format!("{:?}", reject_result)), }, }; diff --git a/state-manager/core-api-server/src/core_api/transactions.rs b/state-manager/core-api-server/src/core_api/transactions.rs index 55f63366ad..f85641ce07 100644 --- a/state-manager/core-api-server/src/core_api/transactions.rs +++ b/state-manager/core-api-server/src/core_api/transactions.rs @@ -10,7 +10,6 @@ use state_manager::store::TransactionStore; use state_manager::{MempoolError, TId, TemporaryTransactionReceipt, Transaction}; use std::cmp; use std::sync::{Arc, Mutex}; -use swagger::Nullable; use transaction::model::NotarizedTransaction as EngineNotarizedTransaction; pub(crate) fn handle_submit_transaction( @@ -191,7 +190,7 @@ fn to_api_committed_transaction( xrd_burned: "0".to_string(), xrd_tipped: "0".to_string(), }, - output: Some(Nullable::Present(vec!["00".to_string()])), // TODO: fixme (needs receipt) + output: Some(vec!["00".to_string()]), // TODO: fixme (needs receipt) error_message: None, // TODO: fixme (needs receipt) }, } From 4a3eb2ea54fb7c1e7b79e299dd739308c4ef2769 Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Mon, 29 Aug 2022 19:03:00 +0200 Subject: [PATCH 6/7] Return error on missing txn state versions --- .../src/core_api/generated/models.rs | 6 +-- .../core-api-server/src/core_api/preview.rs | 6 +-- .../src/core_api/transactions.rs | 54 ++++++++++++++----- 3 files changed, 45 insertions(+), 21 deletions(-) diff --git a/state-manager/core-api-server/src/core_api/generated/models.rs b/state-manager/core-api-server/src/core_api/generated/models.rs index 9bb0d2bd19..81dfa83e1d 100644 --- a/state-manager/core-api-server/src/core_api/generated/models.rs +++ b/state-manager/core-api-server/src/core_api/generated/models.rs @@ -2606,9 +2606,9 @@ pub enum TransactionStatus { impl std::fmt::Display for TransactionStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - TransactionStatus::SUCCEEDED => write!(f, "{}", "succeeded"), - TransactionStatus::FAILED => write!(f, "{}", "failed"), - TransactionStatus::REJECTED => write!(f, "{}", "rejected"), + TransactionStatus::SUCCEEDED => write!(f, "succeeded"), + TransactionStatus::FAILED => write!(f, "failed"), + TransactionStatus::REJECTED => write!(f, "rejected"), } } } diff --git a/state-manager/core-api-server/src/core_api/preview.rs b/state-manager/core-api-server/src/core_api/preview.rs index a4257de5dd..8a584d9c3f 100644 --- a/state-manager/core-api-server/src/core_api/preview.rs +++ b/state-manager/core-api-server/src/core_api/preview.rs @@ -144,11 +144,7 @@ fn to_api_response( let (status, output, error_message) = match commit_result.outcome { TransactionOutcome::Success(output) => { let output_hex = output.into_iter().map(hex::encode).collect(); - ( - TransactionStatus::SUCCEEDED, - Some(output_hex), - None, - ) + (TransactionStatus::SUCCEEDED, Some(output_hex), None) } TransactionOutcome::Failure(error) => ( TransactionStatus::FAILED, diff --git a/state-manager/core-api-server/src/core_api/transactions.rs b/state-manager/core-api-server/src/core_api/transactions.rs index f85641ce07..31c58abf03 100644 --- a/state-manager/core-api-server/src/core_api/transactions.rs +++ b/state-manager/core-api-server/src/core_api/transactions.rs @@ -81,17 +81,21 @@ fn handle_get_committed_transactions_internal( state_manager: Arc>, request: CommittedTransactionsRequest, ) -> Result { - let initial_state_version: u64 = request - .state_version + let start_state_version: u64 = request + .start_state_version .parse() .map_err(|_| transaction_errors::invalid_int_field("state_version"))?; + if start_state_version < 1 { + return Err(transaction_errors::invalid_start_state_version()); + } + let limit: u64 = request .limit .try_into() .map_err(|_| transaction_errors::invalid_int_field("limit"))?; - let state_version_at_limit: u64 = initial_state_version + let state_version_at_limit: u64 = start_state_version .checked_add(limit) .and_then(|v| v.checked_sub(1)) .ok_or_else(|| transaction_errors::invalid_int_field("limit"))?; @@ -106,14 +110,18 @@ fn handle_get_committed_transactions_internal( ); let mut txns = vec![]; - let mut state_version = initial_state_version; + let mut state_version = start_state_version; while state_version <= up_to_state_version_inclusive { - if let Some(next_tid) = locked_state_manager.proof_store.get_tid(state_version) { - let next_tx = locked_state_manager - .transaction_store - .get_transaction(&next_tid); - txns.push((next_tx, state_version)); - } + let next_tid = locked_state_manager + .proof_store + .get_tid(state_version) + .ok_or_else(|| { + transaction_errors::missing_transaction_at_state_version(state_version) + })?; + let next_tx = locked_state_manager + .transaction_store + .get_transaction(&next_tid); + txns.push((next_tx, state_version)); state_version += 1; } @@ -128,8 +136,11 @@ fn handle_get_committed_transactions_internal( }) .collect::, RequestHandlingError>>()?; + let start_state_version = if api_txns.is_empty() { 0 } else { start_state_version }; + Ok(CommittedTransactionsResponse { - state_version: request.state_version, + start_state_version: start_state_version.to_string(), + max_state_version: up_to_state_version_inclusive.to_string(), transactions: api_txns, }) } @@ -191,7 +202,7 @@ fn to_api_committed_transaction( xrd_tipped: "0".to_string(), }, output: Some(vec!["00".to_string()]), // TODO: fixme (needs receipt) - error_message: None, // TODO: fixme (needs receipt) + error_message: None, // TODO: fixme (needs receipt) }, } } @@ -218,7 +229,24 @@ mod transaction_errors { client_error(4, &format!("Invalid integer: {}", field)) } + pub(crate) fn invalid_start_state_version() -> RequestHandlingError { + client_error( + 5, + "start_state_version is invalid (minimum state version is 1)", + ) + } + pub(crate) fn invalid_committed_txn() -> RequestHandlingError { - server_error(5, "Internal server error: invalid committed txn payload") + server_error(6, "Internal server error: invalid committed txn payload") + } + + pub(crate) fn missing_transaction_at_state_version(state_version: u64) -> RequestHandlingError { + server_error( + 7, + &format!( + "A transaction is missing at state version {}", + state_version + ), + ) } } From 1f9e26b4a129014b95441d26ea037ef06cc47a23 Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Mon, 29 Aug 2022 20:26:30 +0200 Subject: [PATCH 7/7] Rename state-manager to core-rust --- .github/workflows/ci.yml | 6 +++--- build.gradle | 4 ++-- cli-tools/build.gradle | 4 ++-- .../README.md | 0 .../build.gradle | 4 ++-- .../java/com/radixdlt/api/CoreApiServer.java | 0 .../com/radixdlt/api/CoreApiServerModule.java | 0 .../exceptions/ManifestCompilationException.java | 0 .../exceptions/StateManagerRuntimeError.java | 0 .../exceptions/StateManagerRuntimeException.java | 0 .../mempool/MempoolDuplicateException.java | 0 .../java/com/radixdlt/mempool/MempoolError.java | 0 .../radixdlt/mempool/MempoolFullException.java | 0 .../com/radixdlt/mempool/MempoolInserter.java | 0 .../java/com/radixdlt/mempool/MempoolReader.java | 0 .../mempool/MempoolRejectedException.java | 0 .../java/com/radixdlt/mempool/RustMempool.java | 0 .../com/radixdlt/mempool/RustMempoolConfig.java | 0 .../java/com/radixdlt/rev2/ComponentAddress.java | 0 .../src/main/java/com/radixdlt/rev2/Decimal.java | 0 .../main/java/com/radixdlt/rev2/LogLevel.java | 0 .../com/radixdlt/rev2/NetworkDefinition.java | 0 .../java/com/radixdlt/rev2/PackageAddress.java | 0 .../java/com/radixdlt/rev2/ResourceAddress.java | 0 .../com/radixdlt/rev2/TransactionHeader.java | 0 .../com/radixdlt/rev2/TransactionStatus.java | 0 .../main/java/com/radixdlt/sbor/NativeCalls.java | 0 .../java/com/radixdlt/sbor/StateManagerSbor.java | 0 .../statecomputer/RustStateComputer.java | 0 .../statecomputer/commit/CommitRequest.java | 0 .../statemanager/CoreApiServerConfig.java | 0 .../statemanager/REv2DatabaseConfig.java | 0 .../com/radixdlt/statemanager/StateManager.java | 0 .../statemanager/StateManagerConfig.java | 0 .../transaction/ExecutedTransactionReceipt.java | 0 .../REv2TransactionAndProofStore.java | 0 .../radixdlt/transaction/TransactionBuilder.java | 0 .../transaction/TransactionBuilderTest.java | 0 {state-manager => core-rust}/Cargo.lock | 0 {state-manager => core-rust}/Cargo.toml | 0 {state-manager => core-rust}/build.gradle | 4 ++-- .../core-api-server/Cargo.toml | 0 .../core-api-server/core-api-spec.yaml | 0 .../scripts/generate-openapi-server.py | 0 .../core-api-server/src/core_api/errors.rs | 0 .../src/core_api/generated/context.rs | 0 .../src/core_api/generated/header.rs | 0 .../src/core_api/generated/mod.rs | 0 .../src/core_api/generated/models.rs | 0 .../src/core_api/generated/server.rs | 0 .../core-api-server/src/core_api/mod.rs | 0 .../src/core_api/network_configuration.rs | 0 .../core-api-server/src/core_api/preview.rs | 0 .../core-api-server/src/core_api/server.rs | 0 .../core-api-server/src/core_api/transactions.rs | 6 +++++- .../core-api-server/src/jni/mod.rs | 0 .../core-api-server/src/lib.rs | 0 .../core-rust/Cargo.toml | 0 .../core-rust/src/lib.rs | 0 .../state-manager/Cargo.toml | 0 .../state-manager/src/jni/dtos/java_structure.rs | 0 .../state-manager/src/jni/dtos/mod.rs | 0 .../state-manager/src/jni/mempool.rs | 0 .../state-manager/src/jni/mod.rs | 0 .../state-manager/src/jni/state_computer/mod.rs | 0 .../state-manager/src/jni/state_manager.rs | 0 .../state-manager/src/jni/transaction_builder.rs | 0 .../state-manager/src/jni/transaction_store.rs | 0 .../state-manager/src/jni/utils.rs | 0 .../state-manager/src/lib.rs | 0 .../state-manager/src/mempool/mod.rs | 0 .../state-manager/src/mempool/simple.rs | 0 .../state-manager/src/query/mod.rs | 0 .../state-manager/src/query/query_db.rs | 0 .../state-manager/src/result.rs | 0 .../state-manager/src/state_manager.rs | 0 .../src/store/in_memory_proof_store.rs | 0 .../src/store/in_memory_transaction_store.rs | 0 .../state-manager/src/store/mod.rs | 0 .../src/store/rocks_db_transaction_store.rs | 0 .../state-manager/src/store/transaction_store.rs | 0 .../src/transaction_builder/builder.rs | 0 .../state-manager/src/transaction_builder/mod.rs | 0 .../state-manager/src/types.rs | 0 core/Makefile | 2 +- core/build.gradle | 10 +++++----- docker/rust-builder/Dockerfile | 16 ++++++++-------- docker/rust-builder/build-sm.yaml | 2 +- settings.gradle | 9 ++++----- 89 files changed, 35 insertions(+), 32 deletions(-) rename {state-manager-bridge => core-rust-bridge}/README.md (100%) rename {state-manager-bridge => core-rust-bridge}/build.gradle (97%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/api/CoreApiServer.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/api/CoreApiServerModule.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/MempoolError.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/MempoolFullException.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/MempoolInserter.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/MempoolReader.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/RustMempool.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/ComponentAddress.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/Decimal.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/LogLevel.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/NetworkDefinition.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/PackageAddress.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/ResourceAddress.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/TransactionHeader.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/rev2/TransactionStatus.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/sbor/NativeCalls.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/sbor/StateManagerSbor.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/statemanager/StateManager.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/main/java/com/radixdlt/transaction/TransactionBuilder.java (100%) rename {state-manager-bridge => core-rust-bridge}/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java (100%) rename {state-manager => core-rust}/Cargo.lock (100%) rename {state-manager => core-rust}/Cargo.toml (100%) rename {state-manager => core-rust}/build.gradle (98%) rename {state-manager => core-rust}/core-api-server/Cargo.toml (100%) rename {state-manager => core-rust}/core-api-server/core-api-spec.yaml (100%) rename {state-manager => core-rust}/core-api-server/scripts/generate-openapi-server.py (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/errors.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/generated/context.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/generated/header.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/generated/mod.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/generated/models.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/generated/server.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/mod.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/network_configuration.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/preview.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/server.rs (100%) rename {state-manager => core-rust}/core-api-server/src/core_api/transactions.rs (98%) rename {state-manager => core-rust}/core-api-server/src/jni/mod.rs (100%) rename {state-manager => core-rust}/core-api-server/src/lib.rs (100%) rename {state-manager => core-rust}/core-rust/Cargo.toml (100%) rename {state-manager => core-rust}/core-rust/src/lib.rs (100%) rename {state-manager => core-rust}/state-manager/Cargo.toml (100%) rename {state-manager => core-rust}/state-manager/src/jni/dtos/java_structure.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/dtos/mod.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/mempool.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/mod.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/state_computer/mod.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/state_manager.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/transaction_builder.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/transaction_store.rs (100%) rename {state-manager => core-rust}/state-manager/src/jni/utils.rs (100%) rename {state-manager => core-rust}/state-manager/src/lib.rs (100%) rename {state-manager => core-rust}/state-manager/src/mempool/mod.rs (100%) rename {state-manager => core-rust}/state-manager/src/mempool/simple.rs (100%) rename {state-manager => core-rust}/state-manager/src/query/mod.rs (100%) rename {state-manager => core-rust}/state-manager/src/query/query_db.rs (100%) rename {state-manager => core-rust}/state-manager/src/result.rs (100%) rename {state-manager => core-rust}/state-manager/src/state_manager.rs (100%) rename {state-manager => core-rust}/state-manager/src/store/in_memory_proof_store.rs (100%) rename {state-manager => core-rust}/state-manager/src/store/in_memory_transaction_store.rs (100%) rename {state-manager => core-rust}/state-manager/src/store/mod.rs (100%) rename {state-manager => core-rust}/state-manager/src/store/rocks_db_transaction_store.rs (100%) rename {state-manager => core-rust}/state-manager/src/store/transaction_store.rs (100%) rename {state-manager => core-rust}/state-manager/src/transaction_builder/builder.rs (100%) rename {state-manager => core-rust}/state-manager/src/transaction_builder/mod.rs (100%) rename {state-manager => core-rust}/state-manager/src/types.rs (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 02c4f4b1fa..308fda00dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,7 +55,7 @@ jobs: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} run: ./gradlew sonarqube local-dev-sm-docker-build: - name: Test state-manager docker build for local development + name: Test core-rust docker build for local development runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -76,8 +76,8 @@ jobs: path: ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} restore-keys: ${{ runner.os }}-gradle - - name: Run local state-manager docker build - run: ./gradlew :state-manager:buildRustForDocker + - name: Run local core-rust docker build + run: ./gradlew :core-rust:buildRustForDocker steadystate-integration: name: Steady state integration tests runs-on: babylon-runner diff --git a/build.gradle b/build.gradle index 4cefb82d50..55980624fa 100644 --- a/build.gradle +++ b/build.gradle @@ -182,12 +182,12 @@ allprojects { tasks.withType(Test) { systemProperty "file.encoding", "UTF-8" jvmArgs("--enable-preview") - systemProperty "java.library.path", "${project(':state-manager').projectDir}/target/debug" + systemProperty "java.library.path", "${project(':core-rust').projectDir}/target/debug" } } subprojects { - if (project.name == "state-manager") { + if (project.name == "core-rust") { // The below is suitable for a java project, not for a rust project return } diff --git a/cli-tools/build.gradle b/cli-tools/build.gradle index 71a1492552..0ebacbd3d9 100644 --- a/cli-tools/build.gradle +++ b/cli-tools/build.gradle @@ -144,7 +144,7 @@ task getClassPathForRadixShell { task getNativeLibPathForRadixShell { doLast { - print "${project(':state-manager').projectDir}/target/debug/" + print "${project(':core-rust').projectDir}/target/debug/" } } @@ -249,7 +249,7 @@ task runAllIntegrationTests(type: Test) { task runP2pTests(type: JavaExec) { classpath = sourceSets.p2pTest.runtimeClasspath - systemProperty "java.library.path", "${project(':state-manager').projectDir}/target/debug/" + systemProperty "java.library.path", "${project(':core-rust').projectDir}/target/debug/" main = "com.radixdlt.p2ptest.LargeMessageTest" } diff --git a/state-manager-bridge/README.md b/core-rust-bridge/README.md similarity index 100% rename from state-manager-bridge/README.md rename to core-rust-bridge/README.md diff --git a/state-manager-bridge/build.gradle b/core-rust-bridge/build.gradle similarity index 97% rename from state-manager-bridge/build.gradle rename to core-rust-bridge/build.gradle index 00f33cb521..d296d9c355 100644 --- a/state-manager-bridge/build.gradle +++ b/core-rust-bridge/build.gradle @@ -79,11 +79,11 @@ compileJava { // This prevents it being output by the jobs EG generateDevUniverse run in quiet mode. Hence, lifecycle. // Side note: The method of using stdout for generateDevUniverse and friends should really be changed. if (System.getenv("SKIP_NATIVE_RUST_BUILD") == "TRUE") { - logger.lifecycle("As SKIP_NATIVE_RUST_BUILD=TRUE, the native state-manager rust build is being skipped at this point.") + logger.lifecycle("As SKIP_NATIVE_RUST_BUILD=TRUE, the native core-rust build is being skipped at this point.") } else { logger.lifecycle("A native debug rust build required for the node to run natively will be run.") logger.lifecycle("This can be skipped with SKIP_NATIVE_RUST_BUILD=TRUE, if the rust is being built separately.") - dependsOn(":state-manager:buildRustDebug") + dependsOn(":core-rust:buildRustDebug") } } diff --git a/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java b/core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java rename to core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java b/core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java rename to core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java b/core-rust-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java rename to core-rust-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java b/core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java rename to core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java b/core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java rename to core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/Decimal.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/Decimal.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/Decimal.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/Decimal.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java b/core-rust-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java rename to core-rust-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java b/core-rust-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java rename to core-rust-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java b/core-rust-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java rename to core-rust-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java b/core-rust-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java rename to core-rust-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java b/core-rust-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java rename to core-rust-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java b/core-rust-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java rename to core-rust-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java b/core-rust-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java rename to core-rust-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java diff --git a/state-manager-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java b/core-rust-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java similarity index 100% rename from state-manager-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java rename to core-rust-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java diff --git a/state-manager/Cargo.lock b/core-rust/Cargo.lock similarity index 100% rename from state-manager/Cargo.lock rename to core-rust/Cargo.lock diff --git a/state-manager/Cargo.toml b/core-rust/Cargo.toml similarity index 100% rename from state-manager/Cargo.toml rename to core-rust/Cargo.toml diff --git a/state-manager/build.gradle b/core-rust/build.gradle similarity index 98% rename from state-manager/build.gradle rename to core-rust/build.gradle index 282198e946..a244bd6c0c 100644 --- a/state-manager/build.gradle +++ b/core-rust/build.gradle @@ -113,7 +113,7 @@ task buildRustForDocker(type: Exec) { ignoreExitValue true if (project.hasProperty('ci')){ workingDir rootProject.projectDir - def outputDir="state-manager/target/$target" + def outputDir="core-rust/target/$target" def rustBuilderRepo = "eu.gcr.io/dev-container-repo/rust-builder-base" def rustCacheRepo = "eu.gcr.io/dev-container-repo/rust-cache-packages" def cacheTag = project.properties['cacheBranch'] ?: "latest" @@ -135,7 +135,7 @@ task buildRustForDocker(type: Exec) { docker build -f docker/rust-builder/Dockerfile \\ --target=artifact --build-arg TARGET=$target --build-arg BUILDKIT_INLINE_CACHE=1 \\ --cache-from=$rustBuilderRepo:$cacheTag --cache-from=$rustCacheRepo:$cacheTag \\ - --output type=local,dest=state-manager/target/$target/${project.property("rustBinaryBuildType")}/ . + --output type=local,dest=core-rust/target/$target/${project.property("rustBinaryBuildType")}/ . docker push $rustBuilderRepo:$cacheTag || true docker push $rustCacheRepo:$cacheTag || true [ -f $outputDir/${project.property("rustBinaryBuildType")}/libcorerust.so ] diff --git a/state-manager/core-api-server/Cargo.toml b/core-rust/core-api-server/Cargo.toml similarity index 100% rename from state-manager/core-api-server/Cargo.toml rename to core-rust/core-api-server/Cargo.toml diff --git a/state-manager/core-api-server/core-api-spec.yaml b/core-rust/core-api-server/core-api-spec.yaml similarity index 100% rename from state-manager/core-api-server/core-api-spec.yaml rename to core-rust/core-api-server/core-api-spec.yaml diff --git a/state-manager/core-api-server/scripts/generate-openapi-server.py b/core-rust/core-api-server/scripts/generate-openapi-server.py similarity index 100% rename from state-manager/core-api-server/scripts/generate-openapi-server.py rename to core-rust/core-api-server/scripts/generate-openapi-server.py diff --git a/state-manager/core-api-server/src/core_api/errors.rs b/core-rust/core-api-server/src/core_api/errors.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/errors.rs rename to core-rust/core-api-server/src/core_api/errors.rs diff --git a/state-manager/core-api-server/src/core_api/generated/context.rs b/core-rust/core-api-server/src/core_api/generated/context.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/generated/context.rs rename to core-rust/core-api-server/src/core_api/generated/context.rs diff --git a/state-manager/core-api-server/src/core_api/generated/header.rs b/core-rust/core-api-server/src/core_api/generated/header.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/generated/header.rs rename to core-rust/core-api-server/src/core_api/generated/header.rs diff --git a/state-manager/core-api-server/src/core_api/generated/mod.rs b/core-rust/core-api-server/src/core_api/generated/mod.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/generated/mod.rs rename to core-rust/core-api-server/src/core_api/generated/mod.rs diff --git a/state-manager/core-api-server/src/core_api/generated/models.rs b/core-rust/core-api-server/src/core_api/generated/models.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/generated/models.rs rename to core-rust/core-api-server/src/core_api/generated/models.rs diff --git a/state-manager/core-api-server/src/core_api/generated/server.rs b/core-rust/core-api-server/src/core_api/generated/server.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/generated/server.rs rename to core-rust/core-api-server/src/core_api/generated/server.rs diff --git a/state-manager/core-api-server/src/core_api/mod.rs b/core-rust/core-api-server/src/core_api/mod.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/mod.rs rename to core-rust/core-api-server/src/core_api/mod.rs diff --git a/state-manager/core-api-server/src/core_api/network_configuration.rs b/core-rust/core-api-server/src/core_api/network_configuration.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/network_configuration.rs rename to core-rust/core-api-server/src/core_api/network_configuration.rs diff --git a/state-manager/core-api-server/src/core_api/preview.rs b/core-rust/core-api-server/src/core_api/preview.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/preview.rs rename to core-rust/core-api-server/src/core_api/preview.rs diff --git a/state-manager/core-api-server/src/core_api/server.rs b/core-rust/core-api-server/src/core_api/server.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/server.rs rename to core-rust/core-api-server/src/core_api/server.rs diff --git a/state-manager/core-api-server/src/core_api/transactions.rs b/core-rust/core-api-server/src/core_api/transactions.rs similarity index 98% rename from state-manager/core-api-server/src/core_api/transactions.rs rename to core-rust/core-api-server/src/core_api/transactions.rs index 31c58abf03..7884887d0b 100644 --- a/state-manager/core-api-server/src/core_api/transactions.rs +++ b/core-rust/core-api-server/src/core_api/transactions.rs @@ -136,7 +136,11 @@ fn handle_get_committed_transactions_internal( }) .collect::, RequestHandlingError>>()?; - let start_state_version = if api_txns.is_empty() { 0 } else { start_state_version }; + let start_state_version = if api_txns.is_empty() { + 0 + } else { + start_state_version + }; Ok(CommittedTransactionsResponse { start_state_version: start_state_version.to_string(), diff --git a/state-manager/core-api-server/src/jni/mod.rs b/core-rust/core-api-server/src/jni/mod.rs similarity index 100% rename from state-manager/core-api-server/src/jni/mod.rs rename to core-rust/core-api-server/src/jni/mod.rs diff --git a/state-manager/core-api-server/src/lib.rs b/core-rust/core-api-server/src/lib.rs similarity index 100% rename from state-manager/core-api-server/src/lib.rs rename to core-rust/core-api-server/src/lib.rs diff --git a/state-manager/core-rust/Cargo.toml b/core-rust/core-rust/Cargo.toml similarity index 100% rename from state-manager/core-rust/Cargo.toml rename to core-rust/core-rust/Cargo.toml diff --git a/state-manager/core-rust/src/lib.rs b/core-rust/core-rust/src/lib.rs similarity index 100% rename from state-manager/core-rust/src/lib.rs rename to core-rust/core-rust/src/lib.rs diff --git a/state-manager/state-manager/Cargo.toml b/core-rust/state-manager/Cargo.toml similarity index 100% rename from state-manager/state-manager/Cargo.toml rename to core-rust/state-manager/Cargo.toml diff --git a/state-manager/state-manager/src/jni/dtos/java_structure.rs b/core-rust/state-manager/src/jni/dtos/java_structure.rs similarity index 100% rename from state-manager/state-manager/src/jni/dtos/java_structure.rs rename to core-rust/state-manager/src/jni/dtos/java_structure.rs diff --git a/state-manager/state-manager/src/jni/dtos/mod.rs b/core-rust/state-manager/src/jni/dtos/mod.rs similarity index 100% rename from state-manager/state-manager/src/jni/dtos/mod.rs rename to core-rust/state-manager/src/jni/dtos/mod.rs diff --git a/state-manager/state-manager/src/jni/mempool.rs b/core-rust/state-manager/src/jni/mempool.rs similarity index 100% rename from state-manager/state-manager/src/jni/mempool.rs rename to core-rust/state-manager/src/jni/mempool.rs diff --git a/state-manager/state-manager/src/jni/mod.rs b/core-rust/state-manager/src/jni/mod.rs similarity index 100% rename from state-manager/state-manager/src/jni/mod.rs rename to core-rust/state-manager/src/jni/mod.rs diff --git a/state-manager/state-manager/src/jni/state_computer/mod.rs b/core-rust/state-manager/src/jni/state_computer/mod.rs similarity index 100% rename from state-manager/state-manager/src/jni/state_computer/mod.rs rename to core-rust/state-manager/src/jni/state_computer/mod.rs diff --git a/state-manager/state-manager/src/jni/state_manager.rs b/core-rust/state-manager/src/jni/state_manager.rs similarity index 100% rename from state-manager/state-manager/src/jni/state_manager.rs rename to core-rust/state-manager/src/jni/state_manager.rs diff --git a/state-manager/state-manager/src/jni/transaction_builder.rs b/core-rust/state-manager/src/jni/transaction_builder.rs similarity index 100% rename from state-manager/state-manager/src/jni/transaction_builder.rs rename to core-rust/state-manager/src/jni/transaction_builder.rs diff --git a/state-manager/state-manager/src/jni/transaction_store.rs b/core-rust/state-manager/src/jni/transaction_store.rs similarity index 100% rename from state-manager/state-manager/src/jni/transaction_store.rs rename to core-rust/state-manager/src/jni/transaction_store.rs diff --git a/state-manager/state-manager/src/jni/utils.rs b/core-rust/state-manager/src/jni/utils.rs similarity index 100% rename from state-manager/state-manager/src/jni/utils.rs rename to core-rust/state-manager/src/jni/utils.rs diff --git a/state-manager/state-manager/src/lib.rs b/core-rust/state-manager/src/lib.rs similarity index 100% rename from state-manager/state-manager/src/lib.rs rename to core-rust/state-manager/src/lib.rs diff --git a/state-manager/state-manager/src/mempool/mod.rs b/core-rust/state-manager/src/mempool/mod.rs similarity index 100% rename from state-manager/state-manager/src/mempool/mod.rs rename to core-rust/state-manager/src/mempool/mod.rs diff --git a/state-manager/state-manager/src/mempool/simple.rs b/core-rust/state-manager/src/mempool/simple.rs similarity index 100% rename from state-manager/state-manager/src/mempool/simple.rs rename to core-rust/state-manager/src/mempool/simple.rs diff --git a/state-manager/state-manager/src/query/mod.rs b/core-rust/state-manager/src/query/mod.rs similarity index 100% rename from state-manager/state-manager/src/query/mod.rs rename to core-rust/state-manager/src/query/mod.rs diff --git a/state-manager/state-manager/src/query/query_db.rs b/core-rust/state-manager/src/query/query_db.rs similarity index 100% rename from state-manager/state-manager/src/query/query_db.rs rename to core-rust/state-manager/src/query/query_db.rs diff --git a/state-manager/state-manager/src/result.rs b/core-rust/state-manager/src/result.rs similarity index 100% rename from state-manager/state-manager/src/result.rs rename to core-rust/state-manager/src/result.rs diff --git a/state-manager/state-manager/src/state_manager.rs b/core-rust/state-manager/src/state_manager.rs similarity index 100% rename from state-manager/state-manager/src/state_manager.rs rename to core-rust/state-manager/src/state_manager.rs diff --git a/state-manager/state-manager/src/store/in_memory_proof_store.rs b/core-rust/state-manager/src/store/in_memory_proof_store.rs similarity index 100% rename from state-manager/state-manager/src/store/in_memory_proof_store.rs rename to core-rust/state-manager/src/store/in_memory_proof_store.rs diff --git a/state-manager/state-manager/src/store/in_memory_transaction_store.rs b/core-rust/state-manager/src/store/in_memory_transaction_store.rs similarity index 100% rename from state-manager/state-manager/src/store/in_memory_transaction_store.rs rename to core-rust/state-manager/src/store/in_memory_transaction_store.rs diff --git a/state-manager/state-manager/src/store/mod.rs b/core-rust/state-manager/src/store/mod.rs similarity index 100% rename from state-manager/state-manager/src/store/mod.rs rename to core-rust/state-manager/src/store/mod.rs diff --git a/state-manager/state-manager/src/store/rocks_db_transaction_store.rs b/core-rust/state-manager/src/store/rocks_db_transaction_store.rs similarity index 100% rename from state-manager/state-manager/src/store/rocks_db_transaction_store.rs rename to core-rust/state-manager/src/store/rocks_db_transaction_store.rs diff --git a/state-manager/state-manager/src/store/transaction_store.rs b/core-rust/state-manager/src/store/transaction_store.rs similarity index 100% rename from state-manager/state-manager/src/store/transaction_store.rs rename to core-rust/state-manager/src/store/transaction_store.rs diff --git a/state-manager/state-manager/src/transaction_builder/builder.rs b/core-rust/state-manager/src/transaction_builder/builder.rs similarity index 100% rename from state-manager/state-manager/src/transaction_builder/builder.rs rename to core-rust/state-manager/src/transaction_builder/builder.rs diff --git a/state-manager/state-manager/src/transaction_builder/mod.rs b/core-rust/state-manager/src/transaction_builder/mod.rs similarity index 100% rename from state-manager/state-manager/src/transaction_builder/mod.rs rename to core-rust/state-manager/src/transaction_builder/mod.rs diff --git a/state-manager/state-manager/src/types.rs b/core-rust/state-manager/src/types.rs similarity index 100% rename from state-manager/state-manager/src/types.rs rename to core-rust/state-manager/src/types.rs diff --git a/core/Makefile b/core/Makefile index d98a0f6100..58ae568b6c 100644 --- a/core/Makefile +++ b/core/Makefile @@ -27,7 +27,7 @@ gcloud-token: gcloud-authenticate .PHONY: build-sm build-sm: gcloud-token - cd .. && SKIP_NATIVE_RUST_BUILD=TRUE ./gradlew :state-manager:buildRustForDocker -Pci=true -PcacheBranch=$(GIT_BRANCH) -PrustBinaryBuildType=release + cd .. && SKIP_NATIVE_RUST_BUILD=TRUE ./gradlew :core-rust:buildRustForDocker -Pci=true -PcacheBranch=$(GIT_BRANCH) -PrustBinaryBuildType=release .PHONY: build build-core: diff --git a/core/build.gradle b/core/build.gradle index e25651a271..3c29feae6c 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -206,7 +206,7 @@ jacocoTestReport { dependencies { implementation project(':olympia-engine') implementation project(':common') - implementation project(':state-manager-bridge') + implementation project(':core-rust-bridge') implementation 'com.fasterxml.jackson.core:jackson-databind' implementation 'io.swagger:swagger-annotations:1.5.0' @@ -294,15 +294,15 @@ ospackage() { if (System.getProperty("os.arch") == "aarch64") { target= "aarch64-unknown-linux-gnu" } - def stateManagerBuildType = project.property("rustBinaryBuildType") + def coreRustBuildType = project.property("rustBinaryBuildType") - from("${project(':state-manager').projectDir}/target/${target}/${stateManagerBuildType}/libcorerust.so") { + from("${project(':core-rust').projectDir}/target/${target}/${coreRustBuildType}/libcorerust.so") { into "/usr/lib/jni/" } // See https://github.com/nebula-plugins/gradle-ospackage-plugin/wiki/Deb-Plugin#basic-usage buildDeb { - dependsOn += [installDist, ":state-manager:buildRustForDocker"] + dependsOn += [installDist, ":core-rust:buildRustForDocker"] version = debSafeVersionName() packageName = debPackageName() @@ -312,7 +312,7 @@ ospackage() { } } buildRpm { - dependsOn += [installDist, ":state-manager:buildRustForDocker"] + dependsOn += [installDist, ":core-rust:buildRustForDocker"] } } diff --git a/docker/rust-builder/Dockerfile b/docker/rust-builder/Dockerfile index e3065f8d1f..00b421ac2b 100644 --- a/docker/rust-builder/Dockerfile +++ b/docker/rust-builder/Dockerfile @@ -29,16 +29,16 @@ ENV CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-linux-gnu-gcc # First - we build a dummy rust file, to cache the compilation of all our dependencies in a Docker layer RUN USER=root cargo new dummy RUN USER=root mkdir -p ./dummy/core-rust/src -RUN USER=root mkdir -p ./dummy/state-manager/src +RUN USER=root mkdir -p ./dummy/core-rust/src RUN USER=root mkdir -p ./dummy/core-api-server/src RUN USER=root touch ./dummy/core-rust/src/lib.rs -RUN USER=root touch ./dummy/state-manager/src/lib.rs +RUN USER=root touch ./dummy/core-rust/src/lib.rs RUN USER=root touch ./dummy/core-api-server/src/lib.rs -COPY state-manager/Cargo.toml ./dummy -COPY state-manager/Cargo.lock ./dummy -COPY state-manager/core-rust/Cargo.toml ./dummy/core-rust -COPY state-manager/state-manager/Cargo.toml ./dummy/state-manager -COPY state-manager/core-api-server/Cargo.toml ./dummy/core-api-server +COPY core-rust/Cargo.toml ./dummy +COPY core-rust/Cargo.lock ./dummy +COPY core-rust/core-rust/Cargo.toml ./dummy/core-rust +COPY core-rust/state-manager/Cargo.toml ./dummy/state-manager +COPY core-rust/core-api-server/Cargo.toml ./dummy/core-api-server RUN mv ./dummy/src/main.rs ./dummy/src/lib.rs WORKDIR /app/dummy @@ -48,7 +48,7 @@ RUN rm -rf /app/dummy/* FROM cache-packages as prod-build WORKDIR /app # Now - we copy in everything, and do the actual built -COPY state-manager ./ +COPY core-rust ./ RUN cargo build --target=$TARGET --release RUN cp -R target/$TARGET/release/libcorerust.so / diff --git a/docker/rust-builder/build-sm.yaml b/docker/rust-builder/build-sm.yaml index 256b212b43..9f17e5e9e6 100644 --- a/docker/rust-builder/build-sm.yaml +++ b/docker/rust-builder/build-sm.yaml @@ -8,5 +8,5 @@ services: dockerfile: Dockerfile target: mapped-volume-build volumes: - - ../../state-manager:/app + - ../../core-rust:/app - .cargo:/usr/local/cargo/registry \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index a3eb87080c..65512bdbf7 100644 --- a/settings.gradle +++ b/settings.gradle @@ -3,13 +3,12 @@ include ':core' include ':cli-tools' include ':olympia-engine' include ':common' -include ':state-manager-bridge' -include ':state-manager' +include ':core-rust-bridge' +include ':core-rust' project(':core').projectDir = new File('core') project(':cli-tools').projectDir = new File('cli-tools') project(':olympia-engine').projectDir = new File('olympia-engine') project(':common').projectDir = new File('common') -project(':state-manager-bridge').projectDir = new File('state-manager-bridge') -project(':state-manager').projectDir = new File('state-manager') - +project(':core-rust-bridge').projectDir = new File('core-rust-bridge') +project(':core-rust').projectDir = new File('core-rust')