Decommision src_common prior to reintroducing it for files common between eth and plugins

This commit is contained in:
Francois Beutin
2024-01-15 17:00:20 +01:00
parent df6a7815a0
commit 5e48f0cf5d
23 changed files with 3 additions and 3 deletions

631
src/ethUstream.c Normal file
View File

@@ -0,0 +1,631 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
#include <stdint.h>
#include <string.h>
#include "ethUstream.h"
#include "ethUtils.h"
#include "utils.h"
#define MAX_INT256 32
#define MAX_ADDRESS 20
void initTx(txContext_t *context,
cx_sha3_t *sha3,
txContent_t *content,
ustreamProcess_t customProcessor,
void *extra) {
memset(context, 0, sizeof(txContext_t));
context->sha3 = sha3;
context->content = content;
context->customProcessor = customProcessor;
context->extra = extra;
context->currentField = RLP_NONE + 1;
cx_keccak_init(context->sha3, 256);
}
uint8_t readTxByte(txContext_t *context) {
uint8_t data;
if (context->commandLength < 1) {
PRINTF("readTxByte Underflow\n");
THROW(EXCEPTION);
}
data = *context->workBuffer;
context->workBuffer++;
context->commandLength--;
if (context->processingField) {
context->currentFieldPos++;
}
if (!(context->processingField && context->fieldSingleByte)) {
cx_hash((cx_hash_t *) context->sha3, 0, &data, 1, NULL, 0);
}
return data;
}
void copyTxData(txContext_t *context, uint8_t *out, uint32_t length) {
if (context->commandLength < length) {
PRINTF("copyTxData Underflow\n");
THROW(EXCEPTION);
}
if (out != NULL) {
memmove(out, context->workBuffer, length);
}
if (!(context->processingField && context->fieldSingleByte)) {
cx_hash((cx_hash_t *) context->sha3, 0, context->workBuffer, length, NULL, 0);
}
context->workBuffer += length;
context->commandLength -= length;
if (context->processingField) {
context->currentFieldPos += length;
}
}
static void processContent(txContext_t *context) {
// Keep the full length for sanity checks, move to the next field
if (!context->currentFieldIsList) {
PRINTF("Invalid type for RLP_CONTENT\n");
THROW(EXCEPTION);
}
context->dataLength = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
static void processAccessList(txContext_t *context) {
if (!context->currentFieldIsList) {
PRINTF("Invalid type for RLP_ACCESS_LIST\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, NULL, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->currentField++;
context->processingField = false;
}
}
static void processType(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_TYPE\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > MAX_INT256) {
PRINTF("Invalid length for RLP_TYPE\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, NULL, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->currentField++;
context->processingField = false;
}
}
static void processChainID(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_CHAINID\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > MAX_INT256) {
PRINTF("Invalid length for RLP_CHAINID\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, context->content->chainID.value, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->content->chainID.length = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
}
static void processNonce(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_NONCE\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > MAX_INT256) {
PRINTF("Invalid length for RLP_NONCE\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, context->content->nonce.value, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->content->nonce.length = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
}
static void processStartGas(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_STARTGAS\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > MAX_INT256) {
PRINTF("Invalid length for RLP_STARTGAS %d\n", context->currentFieldLength);
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, context->content->startgas.value + context->currentFieldPos, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->content->startgas.length = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
}
// Alias over `processStartGas()`.
static void processGasLimit(txContext_t *context) {
processStartGas(context);
}
static void processGasprice(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_GASPRICE\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > MAX_INT256) {
PRINTF("Invalid length for RLP_GASPRICE\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, context->content->gasprice.value + context->currentFieldPos, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->content->gasprice.length = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
}
static void processValue(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_VALUE\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > MAX_INT256) {
PRINTF("Invalid length for RLP_VALUE\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, context->content->value.value + context->currentFieldPos, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->content->value.length = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
}
static void processTo(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_TO\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > MAX_ADDRESS) {
PRINTF("Invalid length for RLP_TO\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, context->content->destination + context->currentFieldPos, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->content->destinationLength = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
}
static void processData(txContext_t *context) {
PRINTF("PROCESS DATA\n");
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_DATA\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
// If there is no data, set dataPresent to false.
if (copySize == 1 && *context->workBuffer == 0x00) {
context->content->dataPresent = false;
}
copyTxData(context, NULL, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
PRINTF("incrementing field\n");
context->currentField++;
context->processingField = false;
}
}
static void processAndDiscard(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for Discarded field\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
copyTxData(context, NULL, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->currentField++;
context->processingField = false;
}
}
static void processV(txContext_t *context) {
if (context->currentFieldIsList) {
PRINTF("Invalid type for RLP_V\n");
THROW(EXCEPTION);
}
if (context->currentFieldLength > sizeof(context->content->v)) {
PRINTF("Invalid length for RLP_V\n");
THROW(EXCEPTION);
}
if (context->currentFieldPos < context->currentFieldLength) {
uint32_t copySize =
MIN(context->commandLength, context->currentFieldLength - context->currentFieldPos);
// Make sure we do not copy more than the size of v.
copySize = MIN(copySize, sizeof(context->content->v));
copyTxData(context, context->content->v + context->currentFieldPos, copySize);
}
if (context->currentFieldPos == context->currentFieldLength) {
context->content->vLength = context->currentFieldLength;
context->currentField++;
context->processingField = false;
}
}
static bool processEIP1559Tx(txContext_t *context) {
switch (context->currentField) {
case EIP1559_RLP_CONTENT: {
processContent(context);
if ((context->processingFlags & TX_FLAG_TYPE) == 0) {
context->currentField++;
}
break;
}
// This gets hit only by Wanchain
case EIP1559_RLP_TYPE: {
processType(context);
break;
}
case EIP1559_RLP_CHAINID: {
processChainID(context);
break;
}
case EIP1559_RLP_NONCE: {
processNonce(context);
break;
}
case EIP1559_RLP_MAX_FEE_PER_GAS: {
processGasprice(context);
break;
}
case EIP1559_RLP_GASLIMIT: {
processGasLimit(context);
break;
}
case EIP1559_RLP_TO: {
processTo(context);
break;
}
case EIP1559_RLP_VALUE: {
processValue(context);
break;
}
case EIP1559_RLP_DATA: {
processData(context);
break;
}
case EIP1559_RLP_ACCESS_LIST: {
processAccessList(context);
break;
}
case EIP1559_RLP_MAX_PRIORITY_FEE_PER_GAS:
processAndDiscard(context);
break;
default:
PRINTF("Invalid RLP decoder context\n");
return true;
}
return false;
}
static bool processEIP2930Tx(txContext_t *context) {
switch (context->currentField) {
case EIP2930_RLP_CONTENT:
processContent(context);
if ((context->processingFlags & TX_FLAG_TYPE) == 0) {
context->currentField++;
}
break;
// This gets hit only by Wanchain
case EIP2930_RLP_TYPE:
processType(context);
break;
case EIP2930_RLP_CHAINID:
processChainID(context);
break;
case EIP2930_RLP_NONCE:
processNonce(context);
break;
case EIP2930_RLP_GASPRICE:
processGasprice(context);
break;
case EIP2930_RLP_GASLIMIT:
processGasLimit(context);
break;
case EIP2930_RLP_TO:
processTo(context);
break;
case EIP2930_RLP_VALUE:
processValue(context);
break;
case EIP2930_RLP_DATA:
processData(context);
break;
case EIP2930_RLP_ACCESS_LIST:
processAccessList(context);
break;
default:
PRINTF("Invalid RLP decoder context\n");
return true;
}
return false;
}
static bool processLegacyTx(txContext_t *context) {
switch (context->currentField) {
case LEGACY_RLP_CONTENT:
processContent(context);
if ((context->processingFlags & TX_FLAG_TYPE) == 0) {
context->currentField++;
}
break;
// This gets hit only by Wanchain
case LEGACY_RLP_TYPE:
processType(context);
break;
case LEGACY_RLP_NONCE:
processNonce(context);
break;
case LEGACY_RLP_GASPRICE:
processGasprice(context);
break;
case LEGACY_RLP_STARTGAS:
processStartGas(context);
break;
case LEGACY_RLP_TO:
processTo(context);
break;
case LEGACY_RLP_VALUE:
processValue(context);
break;
case LEGACY_RLP_DATA:
processData(context);
break;
case LEGACY_RLP_R:
case LEGACY_RLP_S:
processAndDiscard(context);
break;
case LEGACY_RLP_V:
processV(context);
break;
default:
PRINTF("Invalid RLP decoder context\n");
return true;
}
return false;
}
static parserStatus_e parseRLP(txContext_t *context) {
bool canDecode = false;
uint32_t offset;
while (context->commandLength != 0) {
bool valid;
// Feed the RLP buffer until the length can be decoded
context->rlpBuffer[context->rlpBufferPos++] = readTxByte(context);
if (rlpCanDecode(context->rlpBuffer, context->rlpBufferPos, &valid)) {
// Can decode now, if valid
if (!valid) {
PRINTF("RLP pre-decode error\n");
return USTREAM_FAULT;
}
canDecode = true;
break;
}
// Cannot decode yet
// Sanity check
if (context->rlpBufferPos == sizeof(context->rlpBuffer)) {
PRINTF("RLP pre-decode logic error\n");
return USTREAM_FAULT;
}
}
if (!canDecode) {
PRINTF("Can't decode\n");
return USTREAM_PROCESSING;
}
// Ready to process this field
if (!rlpDecodeLength(context->rlpBuffer,
&context->currentFieldLength,
&offset,
&context->currentFieldIsList)) {
PRINTF("RLP decode error\n");
return USTREAM_FAULT;
}
// Ready to process this field
if (offset == 0) {
// Hack for single byte, self encoded
context->workBuffer--;
context->commandLength++;
context->fieldSingleByte = true;
} else {
context->fieldSingleByte = false;
}
context->currentFieldPos = 0;
context->rlpBufferPos = 0;
context->processingField = true;
return USTREAM_CONTINUE;
}
static parserStatus_e processTxInternal(txContext_t *context) {
for (;;) {
customStatus_e customStatus = CUSTOM_NOT_HANDLED;
// EIP 155 style transaction
if (PARSING_IS_DONE(context)) {
PRINTF("parsing is done\n");
return USTREAM_FINISHED;
}
// Old style transaction (pre EIP-155). Transations could just skip `v,r,s` so we needed to
// cut parsing here. commandLength == 0 could happen in two cases :
// 1. We are in an old style transaction : just return `USTREAM_FINISHED`.
// 2. We are at the end of an APDU in a multi-apdu process. This would make us return
// `USTREAM_FINISHED` preemptively. Case number 2 should NOT happen as it is up to
// `ledgerjs` to correctly decrease the size of the APDU (`commandLength`) so that this
// situation doesn't happen.
if ((context->txType == LEGACY && context->currentField == LEGACY_RLP_V) &&
(context->commandLength == 0)) {
context->content->vLength = 0;
PRINTF("finished\n");
return USTREAM_FINISHED;
}
if (context->commandLength == 0) {
PRINTF("Command length done\n");
return USTREAM_PROCESSING;
}
if (!context->processingField) {
parserStatus_e status = parseRLP(context);
if (status != USTREAM_CONTINUE) {
return status;
}
}
if (context->customProcessor != NULL) {
customStatus = context->customProcessor(context);
PRINTF("After customprocessor\n");
switch (customStatus) {
case CUSTOM_NOT_HANDLED:
case CUSTOM_HANDLED:
break;
case CUSTOM_SUSPENDED:
return USTREAM_SUSPENDED;
case CUSTOM_FAULT:
PRINTF("Custom processor aborted\n");
return USTREAM_FAULT;
default:
PRINTF("Unhandled custom processor status\n");
return USTREAM_FAULT;
}
}
if (customStatus == CUSTOM_NOT_HANDLED) {
PRINTF("Current field: %d\n", context->currentField);
switch (context->txType) {
bool fault;
case LEGACY:
fault = processLegacyTx(context);
if (fault) {
return USTREAM_FAULT;
} else {
break;
}
case EIP2930:
fault = processEIP2930Tx(context);
if (fault) {
return USTREAM_FAULT;
} else {
break;
}
case EIP1559:
fault = processEIP1559Tx(context);
if (fault) {
return USTREAM_FAULT;
} else {
break;
}
default:
PRINTF("Transaction type %d is not supported\n", context->txType);
return USTREAM_FAULT;
}
}
}
PRINTF("end of here\n");
}
parserStatus_e processTx(txContext_t *context,
const uint8_t *buffer,
uint32_t length,
uint32_t processingFlags) {
parserStatus_e result;
BEGIN_TRY {
TRY {
context->workBuffer = buffer;
context->commandLength = length;
context->processingFlags = processingFlags;
result = processTxInternal(context);
PRINTF("result: %d\n", result);
}
CATCH_OTHER(e) {
result = USTREAM_FAULT;
}
FINALLY {
}
}
END_TRY;
return result;
}
parserStatus_e continueTx(txContext_t *context) {
parserStatus_e result;
BEGIN_TRY {
TRY {
result = processTxInternal(context);
}
CATCH_OTHER(e) {
result = USTREAM_FAULT;
}
FINALLY {
}
}
END_TRY;
return result;
}

168
src/ethUstream.h Normal file
View File

@@ -0,0 +1,168 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
#ifndef _ETHUSTREAM_H_
#define _ETHUSTREAM_H_
#include <stdbool.h>
#include <stdint.h>
#include "os.h"
#include "cx.h"
struct txContext_t;
typedef enum customStatus_e {
CUSTOM_NOT_HANDLED,
CUSTOM_HANDLED,
CUSTOM_SUSPENDED,
CUSTOM_FAULT
} customStatus_e;
typedef customStatus_e (*ustreamProcess_t)(struct txContext_t *context);
#define TX_FLAG_TYPE 0x01
#define ADDRESS_LENGTH 20
#define INT128_LENGTH 16
#define INT256_LENGTH 32
// First variant of every Tx enum.
#define RLP_NONE 0
#define PARSING_IS_DONE(ctx) \
((ctx->txType == LEGACY && ctx->currentField == LEGACY_RLP_DONE) || \
(ctx->txType == EIP2930 && ctx->currentField == EIP2930_RLP_DONE) || \
(ctx->txType == EIP1559 && ctx->currentField == EIP1559_RLP_DONE))
typedef enum rlpLegacyTxField_e {
LEGACY_RLP_NONE = RLP_NONE,
LEGACY_RLP_CONTENT,
LEGACY_RLP_TYPE, // For wanchain
LEGACY_RLP_NONCE,
LEGACY_RLP_GASPRICE,
LEGACY_RLP_STARTGAS,
LEGACY_RLP_TO,
LEGACY_RLP_VALUE,
LEGACY_RLP_DATA,
LEGACY_RLP_V,
LEGACY_RLP_R,
LEGACY_RLP_S,
LEGACY_RLP_DONE
} rlpLegacyTxField_e;
typedef enum rlpEIP2930TxField_e {
EIP2930_RLP_NONE = RLP_NONE,
EIP2930_RLP_CONTENT,
EIP2930_RLP_TYPE, // For wanchain
EIP2930_RLP_CHAINID,
EIP2930_RLP_NONCE,
EIP2930_RLP_GASPRICE,
EIP2930_RLP_GASLIMIT,
EIP2930_RLP_TO,
EIP2930_RLP_VALUE,
EIP2930_RLP_DATA,
EIP2930_RLP_ACCESS_LIST,
EIP2930_RLP_DONE
} rlpEIP2930TxField_e;
typedef enum rlpEIP1559TxField_e {
EIP1559_RLP_NONE = RLP_NONE,
EIP1559_RLP_CONTENT,
EIP1559_RLP_TYPE, // For wanchain
EIP1559_RLP_CHAINID,
EIP1559_RLP_NONCE,
EIP1559_RLP_MAX_PRIORITY_FEE_PER_GAS,
EIP1559_RLP_MAX_FEE_PER_GAS,
EIP1559_RLP_GASLIMIT,
EIP1559_RLP_TO,
EIP1559_RLP_VALUE,
EIP1559_RLP_DATA,
EIP1559_RLP_ACCESS_LIST,
EIP1559_RLP_DONE
} rlpEIP1559TxField_e;
#define MIN_TX_TYPE 0x00
#define MAX_TX_TYPE 0x7f
// EIP 2718 TransactionType
// Valid transaction types should be in [0x00, 0x7f]
typedef enum txType_e {
EIP2930 = 0x01,
EIP1559 = 0x02,
LEGACY = 0xc0 // Legacy tx are greater than or equal to 0xc0.
} txType_e;
typedef enum parserStatus_e {
USTREAM_PROCESSING, // Parsing is in progress
USTREAM_SUSPENDED, // Parsing has been suspended
USTREAM_FINISHED, // Parsing is done
USTREAM_FAULT, // An error was encountered while parsing
USTREAM_CONTINUE // Used internally to signify we can keep on parsing
} parserStatus_e;
typedef struct txInt256_t {
uint8_t value[INT256_LENGTH];
uint8_t length;
} txInt256_t;
typedef struct txContent_t {
txInt256_t gasprice; // Used as MaxFeePerGas when dealing with EIP1559 transactions.
txInt256_t startgas; // Also known as `gasLimit`.
txInt256_t value;
txInt256_t nonce;
txInt256_t chainID;
uint8_t destination[ADDRESS_LENGTH];
uint8_t destinationLength;
uint8_t v[8];
uint8_t vLength;
bool dataPresent;
} txContent_t;
typedef struct txContext_t {
uint8_t currentField;
cx_sha3_t *sha3;
uint32_t currentFieldLength;
uint32_t currentFieldPos;
bool currentFieldIsList;
bool processingField;
bool fieldSingleByte;
uint32_t dataLength;
uint8_t rlpBuffer[5];
uint32_t rlpBufferPos;
const uint8_t *workBuffer;
uint32_t commandLength;
uint32_t processingFlags;
ustreamProcess_t customProcessor;
txContent_t *content;
void *extra;
uint8_t txType;
} txContext_t;
void initTx(txContext_t *context,
cx_sha3_t *sha3,
txContent_t *content,
ustreamProcess_t customProcessor,
void *extra);
parserStatus_e processTx(txContext_t *context,
const uint8_t *buffer,
uint32_t length,
uint32_t processingFlags);
parserStatus_e continueTx(txContext_t *context);
void copyTxData(txContext_t *context, uint8_t *out, uint32_t length);
uint8_t readTxByte(txContext_t *context);
#endif // _ETHUSTREAM_H_

379
src/ethUtils.c Normal file
View File

@@ -0,0 +1,379 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
/**
* @brief Utilities for an Ethereum Hardware Wallet logic
* @file ethUtils.h
* @author Ledger Firmware Team <hello@ledger.fr>
* @version 1.0
* @date 8th of March 2016
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "shared_context.h"
#include "utils.h"
#include "ethUtils.h"
#include "chainConfig.h"
#include "ethUstream.h"
#include "network.h"
bool rlpCanDecode(uint8_t *buffer, uint32_t bufferLength, bool *valid) {
if (*buffer <= 0x7f) {
} else if (*buffer <= 0xb7) {
} else if (*buffer <= 0xbf) {
if (bufferLength < (1 + (*buffer - 0xb7))) {
return false;
}
if (*buffer > 0xbb) {
*valid = false; // arbitrary 32 bits length limitation
return true;
}
} else if (*buffer <= 0xf7) {
} else {
if (bufferLength < (1 + (*buffer - 0xf7))) {
return false;
}
if (*buffer > 0xfb) {
*valid = false; // arbitrary 32 bits length limitation
return true;
}
}
*valid = true;
return true;
}
bool rlpDecodeLength(uint8_t *buffer, uint32_t *fieldLength, uint32_t *offset, bool *list) {
if (*buffer <= 0x7f) {
*offset = 0;
*fieldLength = 1;
*list = false;
} else if (*buffer <= 0xb7) {
*offset = 1;
*fieldLength = *buffer - 0x80;
*list = false;
} else if (*buffer <= 0xbf) {
*offset = 1 + (*buffer - 0xb7);
*list = false;
switch (*buffer) {
case 0xb8:
*fieldLength = *(buffer + 1);
break;
case 0xb9:
*fieldLength = (*(buffer + 1) << 8) + *(buffer + 2);
break;
case 0xba:
*fieldLength = (*(buffer + 1) << 16) + (*(buffer + 2) << 8) + *(buffer + 3);
break;
case 0xbb:
*fieldLength = (*(buffer + 1) << 24) + (*(buffer + 2) << 16) +
(*(buffer + 3) << 8) + *(buffer + 4);
break;
default:
return false; // arbitrary 32 bits length limitation
}
} else if (*buffer <= 0xf7) {
*offset = 1;
*fieldLength = *buffer - 0xc0;
*list = true;
} else {
*offset = 1 + (*buffer - 0xf7);
*list = true;
switch (*buffer) {
case 0xf8:
*fieldLength = *(buffer + 1);
break;
case 0xf9:
*fieldLength = (*(buffer + 1) << 8) + *(buffer + 2);
break;
case 0xfa:
*fieldLength = (*(buffer + 1) << 16) + (*(buffer + 2) << 8) + *(buffer + 3);
break;
case 0xfb:
*fieldLength = (*(buffer + 1) << 24) + (*(buffer + 2) << 16) +
(*(buffer + 3) << 8) + *(buffer + 4);
break;
default:
return false; // arbitrary 32 bits length limitation
}
}
return true;
}
bool getEthAddressFromKey(cx_ecfp_public_key_t *publicKey, uint8_t *out, cx_sha3_t *sha3Context) {
uint8_t hashAddress[INT256_LENGTH];
if (cx_keccak_init_no_throw(sha3Context, 256) != CX_OK) {
return false;
}
if (cx_hash_no_throw((cx_hash_t *) sha3Context,
CX_LAST,
publicKey->W + 1,
64,
hashAddress,
32) != CX_OK) {
return false;
}
memmove(out, hashAddress + 12, 20);
return true;
}
bool getEthAddressStringFromKey(cx_ecfp_public_key_t *publicKey,
char *out,
cx_sha3_t *sha3Context,
uint64_t chainId) {
uint8_t hashAddress[INT256_LENGTH];
if (cx_keccak_init_no_throw(sha3Context, 256) != CX_OK) {
return false;
}
if (cx_hash_no_throw((cx_hash_t *) sha3Context,
CX_LAST,
publicKey->W + 1,
64,
hashAddress,
32) != CX_OK) {
return false;
}
if (!getEthAddressStringFromBinary(hashAddress + 12, out, sha3Context, chainId)) {
return false;
}
return true;
}
bool u64_to_string(uint64_t src, char *dst, uint8_t dst_size) {
// Copy the numbers in ASCII format.
uint8_t i = 0;
do {
// Checking `i + 1` to make sure we have enough space for '\0'.
if (i + 1 >= dst_size) {
return false;
}
dst[i] = src % 10 + '0';
src /= 10;
i++;
} while (src);
// Null terminate string
dst[i] = '\0';
// Revert the string
i--;
uint8_t j = 0;
while (j < i) {
char tmp = dst[i];
dst[i] = dst[j];
dst[j] = tmp;
i--;
j++;
}
return true;
}
bool getEthAddressStringFromBinary(uint8_t *address,
char *out,
cx_sha3_t *sha3Context,
uint64_t chainId) {
// save some precious stack space
union locals_union {
uint8_t hashChecksum[INT256_LENGTH];
uint8_t tmp[51];
} locals_union;
uint8_t i;
bool eip1191 = false;
uint32_t offset = 0;
switch (chainId) {
case 30:
case 31:
eip1191 = true;
break;
}
if (eip1191) {
if (!u64_to_string(chainId, (char *) locals_union.tmp, sizeof(locals_union.tmp))) {
return false;
}
offset = strnlen((char *) locals_union.tmp, sizeof(locals_union.tmp));
strlcat((char *) locals_union.tmp + offset, "0x", sizeof(locals_union.tmp) - offset);
offset = strnlen((char *) locals_union.tmp, sizeof(locals_union.tmp));
}
for (i = 0; i < 20; i++) {
uint8_t digit = address[i];
locals_union.tmp[offset + 2 * i] = HEXDIGITS[(digit >> 4) & 0x0f];
locals_union.tmp[offset + 2 * i + 1] = HEXDIGITS[digit & 0x0f];
}
if (cx_keccak_init_no_throw(sha3Context, 256) != CX_OK) {
return false;
}
if (cx_hash_no_throw((cx_hash_t *) sha3Context,
CX_LAST,
locals_union.tmp,
offset + 40,
locals_union.hashChecksum,
32) != CX_OK) {
return false;
}
for (i = 0; i < 40; i++) {
uint8_t digit = address[i / 2];
if ((i % 2) == 0) {
digit = (digit >> 4) & 0x0f;
} else {
digit = digit & 0x0f;
}
if (digit < 10) {
out[i] = HEXDIGITS[digit];
} else {
int v = (locals_union.hashChecksum[i / 2] >> (4 * (1 - i % 2))) & 0x0f;
if (v >= 8) {
out[i] = HEXDIGITS[digit] - 'a' + 'A';
} else {
out[i] = HEXDIGITS[digit];
}
}
}
out[40] = '\0';
return true;
}
/* Fills the `out` buffer with the lowercase string representation of the pubkey passed in as binary
format by `in`. (eg: uint8_t*:0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB ->
char*:"0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB\0" )
`sha3` context doesn't have have to be initialized prior to call.*/
bool getEthDisplayableAddress(uint8_t *in,
char *out,
size_t out_len,
cx_sha3_t *sha3,
uint64_t chainId) {
if (out_len < 43) {
strlcpy(out, "ERROR", out_len);
return false;
}
out[0] = '0';
out[1] = 'x';
if (!getEthAddressStringFromBinary(in, out + 2, sha3, chainId)) {
strlcpy(out, "ERROR", out_len);
return false;
}
return true;
}
bool adjustDecimals(const char *src,
size_t srcLength,
char *target,
size_t targetLength,
uint8_t decimals) {
uint32_t startOffset;
uint32_t lastZeroOffset = 0;
uint32_t offset = 0;
if ((srcLength == 1) && (*src == '0')) {
if (targetLength < 2) {
return false;
}
target[0] = '0';
target[1] = '\0';
return true;
}
if (srcLength <= decimals) {
uint32_t delta = decimals - srcLength;
if (targetLength < srcLength + 1 + 2 + delta) {
return false;
}
target[offset++] = '0';
target[offset++] = '.';
for (uint32_t i = 0; i < delta; i++) {
target[offset++] = '0';
}
startOffset = offset;
for (uint32_t i = 0; i < srcLength; i++) {
target[offset++] = src[i];
}
target[offset] = '\0';
} else {
uint32_t sourceOffset = 0;
uint32_t delta = srcLength - decimals;
if (targetLength < srcLength + 1 + 1) {
return false;
}
while (offset < delta) {
target[offset++] = src[sourceOffset++];
}
if (decimals != 0) {
target[offset++] = '.';
}
startOffset = offset;
while (sourceOffset < srcLength) {
target[offset++] = src[sourceOffset++];
}
target[offset] = '\0';
}
for (uint32_t i = startOffset; i < offset; i++) {
if (target[i] == '0') {
if (lastZeroOffset == 0) {
lastZeroOffset = i;
}
} else {
lastZeroOffset = 0;
}
}
if (lastZeroOffset != 0) {
target[lastZeroOffset] = '\0';
if (target[lastZeroOffset - 1] == '.') {
target[lastZeroOffset - 1] = '\0';
}
}
return true;
}
// Returns the chain ID. Defaults to 0 if txType was not found (For TX).
uint64_t get_tx_chain_id(void) {
uint64_t chain_id = 0;
switch (txContext.txType) {
case LEGACY:
chain_id = u64_from_BE(txContext.content->v, txContext.content->vLength);
break;
case EIP2930:
case EIP1559:
chain_id = u64_from_BE(tmpContent.txContent.chainID.value,
tmpContent.txContent.chainID.length);
break;
default:
PRINTF("Txtype `%d` not supported while generating chainID\n", txContext.txType);
break;
}
return chain_id;
}
const char *get_displayable_ticker(const uint64_t *chain_id) {
const char *ticker = get_network_ticker_from_chain_id(chain_id);
if (ticker == NULL) {
ticker = chainConfig->coinName;
}
return ticker;
}

93
src/ethUtils.h Normal file
View File

@@ -0,0 +1,93 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
#ifndef _ETHUTILS_H_
#define _ETHUTILS_H_
#include <stdint.h>
#include "cx.h"
#include "chainConfig.h"
#define KECCAK256_HASH_BYTESIZE 32
/**
* @brief Decode an RLP encoded field - see
* https://github.com/ethereum/wiki/wiki/RLP
* @param [in] buffer buffer containing the RLP encoded field to decode
* @param [out] fieldLength length of the RLP encoded field
* @param [out] offset offset to the beginning of the RLP encoded field from the
* buffer
* @param [out] list true if the field encodes a list, false if it encodes a
* string
* @return true if the RLP header is consistent
*/
bool rlpDecodeLength(uint8_t *buffer, uint32_t *fieldLength, uint32_t *offset, bool *list);
bool rlpCanDecode(uint8_t *buffer, uint32_t bufferLength, bool *valid);
bool getEthAddressFromKey(cx_ecfp_public_key_t *publicKey, uint8_t *out, cx_sha3_t *sha3Context);
bool getEthAddressStringFromKey(cx_ecfp_public_key_t *publicKey,
char *out,
cx_sha3_t *sha3Context,
uint64_t chainId);
bool u64_to_string(uint64_t src, char *dst, uint8_t dst_size);
bool getEthAddressStringFromBinary(uint8_t *address,
char *out,
cx_sha3_t *sha3Context,
uint64_t chainId);
bool getEthDisplayableAddress(uint8_t *in,
char *out,
size_t out_len,
cx_sha3_t *sha3,
uint64_t chainId);
bool adjustDecimals(const char *src,
size_t srcLength,
char *target,
size_t targetLength,
uint8_t decimals);
static __attribute__((no_instrument_function)) inline int allzeroes(const void *buf, size_t n) {
uint8_t *p = (uint8_t *) buf;
for (size_t i = 0; i < n; ++i) {
if (p[i]) {
return 0;
}
}
return 1;
}
static __attribute__((no_instrument_function)) inline int ismaxint(uint8_t *buf, int n) {
for (int i = 0; i < n; ++i) {
if (buf[i] != 0xff) {
return 0;
}
}
return 1;
}
uint64_t get_tx_chain_id(void);
const char *get_displayable_ticker(const uint64_t *chain_id);
static const char HEXDIGITS[] = "0123456789abcdef";
#endif // _ETHUTILS_H_

22
src/hash_bytes.c Normal file
View File

@@ -0,0 +1,22 @@
#include "hash_bytes.h"
/**
* Continue given progressive hash on given bytes
*
* @param[in] bytes_ptr pointer to bytes
* @param[in] n number of bytes to hash
* @param[in] hash_ctx pointer to the hashing context
*/
void hash_nbytes(const uint8_t *bytes_ptr, size_t n, cx_hash_t *hash_ctx) {
cx_hash(hash_ctx, 0, bytes_ptr, n, NULL, 0);
}
/**
* Continue given progressive hash on given byte
*
* @param[in] byte byte to hash
* @param[in] hash_ctx pointer to the hashing context
*/
void hash_byte(uint8_t byte, cx_hash_t *hash_ctx) {
hash_nbytes(&byte, 1, hash_ctx);
}

10
src/hash_bytes.h Normal file
View File

@@ -0,0 +1,10 @@
#ifndef HASH_BYTES_H_
#define HASH_BYTES_H_
#include <stdint.h>
#include "cx.h"
void hash_nbytes(const uint8_t *const bytes_ptr, size_t n, cx_hash_t *hash_ctx);
void hash_byte(uint8_t byte, cx_hash_t *hash_ctx);
#endif // HASH_BYTES_H_

65
src/mem.c Normal file
View File

@@ -0,0 +1,65 @@
/**
* Dynamic allocator that uses a fixed-length buffer that is hopefully big enough
*
* The two functions alloc & dealloc use the buffer as a simple stack.
* Especially useful when an unpredictable amount of data will be received and have to be stored
* during the transaction but discarded right after.
*/
#ifdef HAVE_DYN_MEM_ALLOC
#include <stdint.h>
#include "mem.h"
#define SIZE_MEM_BUFFER 8192
static uint8_t mem_buffer[SIZE_MEM_BUFFER];
static size_t mem_idx;
/**
* Initializes the memory buffer index
*/
void mem_init(void) {
mem_idx = 0;
}
/**
* Resets the memory buffer index
*/
void mem_reset(void) {
mem_init();
}
/**
* Allocates (push) a chunk of the memory buffer of a given size.
*
* Checks to see if there are enough space left in the memory buffer, returns
* the current location in the memory buffer and moves the index accordingly.
*
* @param[in] size Requested allocation size in bytes
* @return Allocated memory pointer; \ref NULL if not enough space left.
*/
void *mem_alloc(size_t size) {
if ((mem_idx + size) > SIZE_MEM_BUFFER) // Buffer exceeded
{
return NULL;
}
mem_idx += size;
return &mem_buffer[mem_idx - size];
}
/**
* De-allocates (pop) a chunk of memory buffer by a given size.
*
* @param[in] size Requested deallocation size in bytes
*/
void mem_dealloc(size_t size) {
if (size > mem_idx) // More than is already allocated
{
mem_idx = 0;
} else {
mem_idx -= size;
}
}
#endif // HAVE_DYN_MEM_ALLOC

15
src/mem.h Normal file
View File

@@ -0,0 +1,15 @@
#ifndef MEM_H_
#define MEM_H_
#ifdef HAVE_DYN_MEM_ALLOC
#include <stdlib.h>
void mem_init(void);
void mem_reset(void);
void *mem_alloc(size_t size);
void mem_dealloc(size_t size);
#endif // HAVE_DYN_MEM_ALLOC
#endif // MEM_H_

60
src/mem_utils.c Normal file
View File

@@ -0,0 +1,60 @@
#ifdef HAVE_DYN_MEM_ALLOC
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "mem.h"
#include "mem_utils.h"
/**
* Format an unsigned number up to 32-bit into memory into an ASCII string.
*
* @param[in] value Value to write in memory
* @param[out] length number of characters written to memory
*
* @return pointer to memory area or \ref NULL if the allocation failed
*/
char *mem_alloc_and_format_uint(uint32_t value, uint8_t *const length) {
char *mem_ptr;
uint32_t value_copy;
uint8_t size;
size = 1; // minimum size, even if 0
value_copy = value;
while (value_copy >= 10) {
value_copy /= 10;
size += 1;
}
// +1 for the null character
if ((mem_ptr = mem_alloc(sizeof(char) * (size + 1)))) {
snprintf(mem_ptr, (size + 1), "%u", value);
mem_dealloc(sizeof(char)); // to skip the null character
if (length != NULL) {
*length = size;
}
}
return mem_ptr;
}
/**
* Allocate and align, required when dealing with pointers of multi-bytes data
* like structures that will be dereferenced at runtime.
*
* @param[in] size the size of the data we want to allocate in memory
* @param[in] alignment the byte alignment needed
*
* @return pointer to the memory area, \ref NULL if the allocation failed
*/
void *mem_alloc_and_align(size_t size, size_t alignment) {
uint8_t align_diff = (uintptr_t) mem_alloc(0) % alignment;
if (align_diff > 0) // alignment needed
{
if (mem_alloc(alignment - align_diff) == NULL) {
return NULL;
}
}
return mem_alloc(size);
}
#endif // HAVE_DYN_MEM_ALLOC

16
src/mem_utils.h Normal file
View File

@@ -0,0 +1,16 @@
#ifndef MEM_UTILS_H_
#define MEM_UTILS_H_
#ifdef HAVE_DYN_MEM_ALLOC
#include <stdint.h>
#include <stdbool.h>
#define MEM_ALLOC_AND_ALIGN_TYPE(type) mem_alloc_and_align(sizeof(type), __alignof__(type))
char *mem_alloc_and_format_uint(uint32_t value, uint8_t *const written_chars);
void *mem_alloc_and_align(size_t size, size_t alignment);
#endif // HAVE_DYN_MEM_ALLOC
#endif // MEM_UTILS_H_

115
src/network.c Normal file
View File

@@ -0,0 +1,115 @@
#include <string.h>
#include "os_utils.h"
#include "os_pic.h"
#include "network.h"
typedef struct network_info_s {
const char *name;
const char *ticker;
uint64_t chain_id;
} network_info_t;
// Mappping of chain ids to networks.
static const network_info_t NETWORK_MAPPING[] = {
{.chain_id = 1, .name = "Ethereum", .ticker = "ETH"},
{.chain_id = 3, .name = "Ropsten", .ticker = "ETH"},
{.chain_id = 4, .name = "Rinkeby", .ticker = "ETH"},
{.chain_id = 5, .name = "Goerli", .ticker = "ETH"},
{.chain_id = 10, .name = "Optimism", .ticker = "ETH"},
{.chain_id = 42, .name = "LUKSO", .ticker = "LYX"},
{.chain_id = 4201, .name = "LUKSO Testnet", .ticker = "LYXt"},
{.chain_id = 56, .name = "BSC", .ticker = "BNB"},
{.chain_id = 100, .name = "Gnosis", .ticker = "xDAI"},
{.chain_id = 10200, .name = "Chiado", .ticker = "xDAI"},
{.chain_id = 137, .name = "Polygon", .ticker = "MATIC"},
{.chain_id = 250, .name = "Fantom", .ticker = "FTM"},
{.chain_id = 42161, .name = "Arbitrum", .ticker = "ETH"},
{.chain_id = 42220, .name = "Celo", .ticker = "CELO"},
{.chain_id = 43114, .name = "Avalanche", .ticker = "AVAX"},
{.chain_id = 44787, .name = "Celo Alfajores", .ticker = "aCELO"},
{.chain_id = 62320, .name = "Celo Baklava", .ticker = "bCELO"},
{.chain_id = 11297108109, .name = "Palm Network", .ticker = "PALM"},
{.chain_id = 1818, .name = "Cube", .ticker = "CUBE"},
{.chain_id = 336, .name = "Shiden", .ticker = "SDN"},
{.chain_id = 592, .name = "Astar", .ticker = "ASTR"},
{.chain_id = 50, .name = "XDC", .ticker = "XDC"},
{.chain_id = 82, .name = "Meter", .ticker = "MTR"},
{.chain_id = 62621, .name = "Multivac", .ticker = "MTV"},
{.chain_id = 20531812, .name = "Tecra", .ticker = "TCR"},
{.chain_id = 20531811, .name = "TecraTestnet", .ticker = "TCR"},
{.chain_id = 51, .name = "Apothemnetwork", .ticker = "XDC"},
{.chain_id = 199, .name = "BTTC", .ticker = "BTT"},
{.chain_id = 1030, .name = "Conflux", .ticker = "CFX"},
{.chain_id = 61, .name = "Ethereum Classic", .ticker = "ETC"},
{.chain_id = 246, .name = "EnergyWebChain", .ticker = "EWT"},
{.chain_id = 14, .name = "Flare", .ticker = "FLR"},
{.chain_id = 16, .name = "Flare Coston", .ticker = "FLR"},
{.chain_id = 24, .name = "KardiaChain", .ticker = "KAI"},
{.chain_id = 1284, .name = "Moonbeam", .ticker = "GLMR"},
{.chain_id = 1285, .name = "Moonriver", .ticker = "MOVR"},
{.chain_id = 66, .name = "OKXChain", .ticker = "OKT"},
{.chain_id = 99, .name = "POA", .ticker = "POA"},
{.chain_id = 7341, .name = "Shyft", .ticker = "SHFT"},
{.chain_id = 19, .name = "Songbird", .ticker = "SGB"},
{.chain_id = 73799, .name = "Volta", .ticker = "VOLTA"},
{.chain_id = 25, .name = "Cronos", .ticker = "CRO"},
{.chain_id = 534353, .name = "Scroll Alpha", .ticker = "ETH"},
{.chain_id = 534351, .name = "Scroll Sepolia", .ticker = "ETH"},
{.chain_id = 534352, .name = "Scroll", .ticker = "ETH"},
{.chain_id = 321, .name = "KCC", .ticker = "KCS"},
{.chain_id = 30, .name = "Rootstock", .ticker = "RBTC"},
{.chain_id = 9001, .name = "Evmos", .ticker = "EVMOS"},
{.chain_id = 1088, .name = "Metis Andromeda", .ticker = "METIS"},
{.chain_id = 2222, .name = "Kava EVM", .ticker = "KAVA"},
{.chain_id = 8217, .name = "Klaytn Cypress", .ticker = "KLAY"},
{.chain_id = 57, .name = "Syscoin", .ticker = "SYS"},
{.chain_id = 106, .name = "Velas EVM", .ticker = "VLX"},
{.chain_id = 288, .name = "Boba Network", .ticker = "ETH"},
{.chain_id = 39797, .name = "Energi", .ticker = "NRG"},
{.chain_id = 369, .name = "PulseChain", .ticker = "PLS"},
{.chain_id = 245022926, .name = "Neon EVM Devnet", .ticker = "NEON"},
{.chain_id = 245022934, .name = "Neon EVM Mainnet", .ticker = "NEON"},
{.chain_id = 4919, .name = "Venidium", .ticker = "XVM"},
{.chain_id = 40, .name = "Telos EVM Mainnet", .ticker = "TLOS"},
{.chain_id = 196, .name = "OKBChain Mainnet", .ticker = "OKB"},
{.chain_id = 248, .name = "Oasys", .ticker = "OAS"},
{.chain_id = 1101, .name = "Polygon zkEVM", .ticker = "ETH"},
{.chain_id = 8453, .name = "Base", .ticker = "ETH"},
{.chain_id = 58008, .name = "Sepolia", .ticker = "ETH"},
{.chain_id = 1907, .name = "Bitcichain", .ticker = "BITCI"},
{.chain_id = 1116, .name = "Core", .ticker = "CORE"},
{.chain_id = 7171, .name = "Bitrock Mainnet", .ticker = "BROCK"},
{.chain_id = 10507, .name = "Numbers Protocol", .ticker = "NUM"},
{.chain_id = 59144, .name = "Linea", .ticker = "ETH"},
};
static const network_info_t *get_network_from_chain_id(const uint64_t *chain_id) {
for (size_t i = 0; i < ARRAYLEN(NETWORK_MAPPING); i++) {
if (NETWORK_MAPPING[i].chain_id == *chain_id) {
return (const network_info_t *) &NETWORK_MAPPING[i];
}
}
return NULL;
}
const char *get_network_name_from_chain_id(const uint64_t *chain_id) {
const network_info_t *net = get_network_from_chain_id(chain_id);
if (net == NULL) {
return NULL;
}
return PIC(net->name);
}
const char *get_network_ticker_from_chain_id(const uint64_t *chain_id) {
const network_info_t *net = get_network_from_chain_id(chain_id);
if (net == NULL) {
return NULL;
}
return PIC(net->ticker);
}
bool chain_is_ethereum_compatible(const uint64_t *chain_id) {
return get_network_from_chain_id(chain_id) != NULL;
}

12
src/network.h Normal file
View File

@@ -0,0 +1,12 @@
#ifndef _NETWORK_H_
#define _NETWORK_H_
#include <stdint.h>
#include <stdbool.h>
const char *get_network_name_from_chain_id(const uint64_t *chain_id);
const char *get_network_ticker_from_chain_id(const uint64_t *chain_id);
bool chain_is_ethereum_compatible(const uint64_t *chain_id);
#endif // _NETWORK_H_

40
src/plugins.c Normal file
View File

@@ -0,0 +1,40 @@
#include "eth_plugin_handler.h"
#include "ui_callbacks.h"
void plugin_ui_get_id(void) {
ethQueryContractID_t pluginQueryContractID;
eth_plugin_prepare_query_contract_ID(&pluginQueryContractID,
strings.common.fullAddress,
sizeof(strings.common.fullAddress),
strings.common.fullAmount,
sizeof(strings.common.fullAmount));
// Query the original contract for ID if it's not an internal alias
if (!eth_plugin_call(ETH_PLUGIN_QUERY_CONTRACT_ID, (void *) &pluginQueryContractID)) {
PRINTF("Plugin query contract ID call failed\n");
io_seproxyhal_touch_tx_cancel(NULL);
}
}
void plugin_ui_get_item_internal(char *title_buffer,
size_t title_buffer_size,
char *msg_buffer,
size_t msg_buffer_size) {
ethQueryContractUI_t pluginQueryContractUI;
eth_plugin_prepare_query_contract_UI(&pluginQueryContractUI,
dataContext.tokenContext.pluginUiCurrentItem,
title_buffer,
title_buffer_size,
msg_buffer,
msg_buffer_size);
if (!eth_plugin_call(ETH_PLUGIN_QUERY_CONTRACT_UI, (void *) &pluginQueryContractUI)) {
PRINTF("Plugin query contract UI call failed\n");
io_seproxyhal_touch_tx_cancel(NULL);
}
}
void plugin_ui_get_item(void) {
plugin_ui_get_item_internal(strings.common.fullAddress,
sizeof(strings.common.fullAddress),
strings.common.fullAmount,
sizeof(strings.common.fullAmount));
}

11
src/plugins.h Normal file
View File

@@ -0,0 +1,11 @@
#ifndef _PLUGIN_H_
#define _PLUGIN_H_
void plugin_ui_get_id();
void plugin_ui_get_item();
void plugin_ui_get_item_internal(uint8_t *title_buffer,
size_t title_buffer_size,
uint8_t *msg_buffer,
size_t msg_buffer_size);
#endif // _PLUGIN_H_

17
src/starkDisplayUtils.c Normal file
View File

@@ -0,0 +1,17 @@
#ifdef HAVE_STARKWARE
#include "shared_context.h"
void stark_sign_display_master_account() {
snprintf(strings.tmp.tmp,
sizeof(strings.tmp.tmp),
"0x%.*H",
32,
dataContext.starkContext.transferDestination);
}
void stark_sign_display_condition_fact() {
snprintf(strings.tmp.tmp, sizeof(strings.tmp.tmp), "0x%.*H", 32, dataContext.starkContext.fact);
}
#endif

6
src/starkDisplayUtils.h Normal file
View File

@@ -0,0 +1,6 @@
#ifdef HAVE_STARKWARE
void stark_sign_display_master_account();
void stark_sign_display_condition_fact();
#endif

292
src/uint128.c Normal file
View File

@@ -0,0 +1,292 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
// Adapted from https://github.com/calccrypto/uint256_t
#include <stdio.h>
#include <string.h>
#include "uint128.h"
#include "uint_common.h"
#include "ethUtils.h" // HEXDIGITS
void readu128BE(const uint8_t *const buffer, uint128_t *const target) {
UPPER_P(target) = readUint64BE(buffer);
LOWER_P(target) = readUint64BE(buffer + 8);
}
bool zero128(const uint128_t *const number) {
return ((LOWER_P(number) == 0) && (UPPER_P(number) == 0));
}
void copy128(uint128_t *const target, const uint128_t *const number) {
UPPER_P(target) = UPPER_P(number);
LOWER_P(target) = LOWER_P(number);
}
void clear128(uint128_t *const target) {
UPPER_P(target) = 0;
LOWER_P(target) = 0;
}
void shiftl128(const uint128_t *const number, uint32_t value, uint128_t *const target) {
if (value >= 128) {
clear128(target);
} else if (value == 64) {
UPPER_P(target) = LOWER_P(number);
LOWER_P(target) = 0;
} else if (value == 0) {
copy128(target, number);
} else if (value < 64) {
UPPER_P(target) = (UPPER_P(number) << value) + (LOWER_P(number) >> (64 - value));
LOWER_P(target) = (LOWER_P(number) << value);
} else if ((128 > value) && (value > 64)) {
UPPER_P(target) = LOWER_P(number) << (value - 64);
LOWER_P(target) = 0;
} else {
clear128(target);
}
}
void shiftr128(const uint128_t *const number, uint32_t value, uint128_t *const target) {
if (value >= 128) {
clear128(target);
} else if (value == 64) {
UPPER_P(target) = 0;
LOWER_P(target) = UPPER_P(number);
} else if (value == 0) {
copy128(target, number);
} else if (value < 64) {
uint128_t result;
UPPER(result) = UPPER_P(number) >> value;
LOWER(result) = (UPPER_P(number) << (64 - value)) + (LOWER_P(number) >> value);
copy128(target, &result);
} else if ((128 > value) && (value > 64)) {
LOWER_P(target) = UPPER_P(number) >> (value - 64);
UPPER_P(target) = 0;
} else {
clear128(target);
}
}
uint32_t bits128(const uint128_t *const number) {
uint32_t result = 0;
if (UPPER_P(number)) {
result = 64;
uint64_t up = UPPER_P(number);
while (up) {
up >>= 1;
result++;
}
} else {
uint64_t low = LOWER_P(number);
while (low) {
low >>= 1;
result++;
}
}
return result;
}
bool equal128(const uint128_t *const number1, const uint128_t *const number2) {
return (UPPER_P(number1) == UPPER_P(number2)) && (LOWER_P(number1) == LOWER_P(number2));
}
bool gt128(const uint128_t *const number1, const uint128_t *const number2) {
if (UPPER_P(number1) == UPPER_P(number2)) {
return (LOWER_P(number1) > LOWER_P(number2));
}
return (UPPER_P(number1) > UPPER_P(number2));
}
bool gte128(const uint128_t *const number1, const uint128_t *const number2) {
return gt128(number1, number2) || equal128(number1, number2);
}
void add128(const uint128_t *const number1,
const uint128_t *const number2,
uint128_t *const target) {
UPPER_P(target) = UPPER_P(number1) + UPPER_P(number2) +
((LOWER_P(number1) + LOWER_P(number2)) < LOWER_P(number1));
LOWER_P(target) = LOWER_P(number1) + LOWER_P(number2);
}
void sub128(const uint128_t *const number1,
const uint128_t *const number2,
uint128_t *const target) {
UPPER_P(target) = UPPER_P(number1) - UPPER_P(number2) -
((LOWER_P(number1) - LOWER_P(number2)) > LOWER_P(number1));
LOWER_P(target) = LOWER_P(number1) - LOWER_P(number2);
}
void or128(const uint128_t *const number1,
const uint128_t *const number2,
uint128_t *const target) {
UPPER_P(target) = UPPER_P(number1) | UPPER_P(number2);
LOWER_P(target) = LOWER_P(number1) | LOWER_P(number2);
}
void mul128(const uint128_t *const number1,
const uint128_t *const number2,
uint128_t *const target) {
uint64_t top[4] = {UPPER_P(number1) >> 32,
UPPER_P(number1) & 0xffffffff,
LOWER_P(number1) >> 32,
LOWER_P(number1) & 0xffffffff};
uint64_t bottom[4] = {UPPER_P(number2) >> 32,
UPPER_P(number2) & 0xffffffff,
LOWER_P(number2) >> 32,
LOWER_P(number2) & 0xffffffff};
uint64_t products[4][4];
uint128_t tmp, tmp2;
for (int y = 3; y > -1; y--) {
for (int x = 3; x > -1; x--) {
products[3 - x][y] = top[x] * bottom[y];
}
}
uint64_t fourth32 = products[0][3] & 0xffffffff;
uint64_t third32 = (products[0][2] & 0xffffffff) + (products[0][3] >> 32);
uint64_t second32 = (products[0][1] & 0xffffffff) + (products[0][2] >> 32);
uint64_t first32 = (products[0][0] & 0xffffffff) + (products[0][1] >> 32);
third32 += products[1][3] & 0xffffffff;
second32 += (products[1][2] & 0xffffffff) + (products[1][3] >> 32);
first32 += (products[1][1] & 0xffffffff) + (products[1][2] >> 32);
second32 += products[2][3] & 0xffffffff;
first32 += (products[2][2] & 0xffffffff) + (products[2][3] >> 32);
first32 += products[3][3] & 0xffffffff;
UPPER(tmp) = first32 << 32;
LOWER(tmp) = 0;
UPPER(tmp2) = third32 >> 32;
LOWER(tmp2) = third32 << 32;
add128(&tmp, &tmp2, target);
UPPER(tmp) = second32;
LOWER(tmp) = 0;
add128(&tmp, target, &tmp2);
UPPER(tmp) = 0;
LOWER(tmp) = fourth32;
add128(&tmp, &tmp2, target);
}
void divmod128(const uint128_t *const l,
const uint128_t *const r,
uint128_t *const retDiv,
uint128_t *const retMod) {
uint128_t copyd, adder, resDiv, resMod;
uint128_t one;
UPPER(one) = 0;
LOWER(one) = 1;
uint32_t diffBits = bits128(l) - bits128(r);
clear128(&resDiv);
copy128(&resMod, l);
if (gt128(r, l)) {
copy128(retMod, l);
clear128(retDiv);
} else {
shiftl128(r, diffBits, &copyd);
shiftl128(&one, diffBits, &adder);
if (gt128(&copyd, &resMod)) {
shiftr128(&copyd, 1, &copyd);
shiftr128(&adder, 1, &adder);
}
while (gte128(&resMod, r)) {
if (gte128(&resMod, &copyd)) {
sub128(&resMod, &copyd, &resMod);
or128(&resDiv, &adder, &resDiv);
}
shiftr128(&copyd, 1, &copyd);
shiftr128(&adder, 1, &adder);
}
copy128(retDiv, &resDiv);
copy128(retMod, &resMod);
}
}
bool tostring128(const uint128_t *const number,
uint32_t baseParam,
char *const out,
uint32_t outLength) {
uint128_t rDiv;
uint128_t rMod;
uint128_t base;
copy128(&rDiv, number);
clear128(&rMod);
clear128(&base);
LOWER(base) = baseParam;
uint32_t offset = 0;
if ((baseParam < 2) || (baseParam > 16)) {
return false;
}
do {
if (offset > (outLength - 1)) {
return false;
}
divmod128(&rDiv, &base, &rDiv, &rMod);
out[offset++] = HEXDIGITS[(uint8_t) LOWER(rMod)];
} while (!zero128(&rDiv));
if (offset > (outLength - 1)) {
return false;
}
out[offset] = '\0';
reverseString(out, offset);
return true;
}
/**
* Format a uint128_t into a string as a signed integer
*
* @param[in] number the number to format
* @param[in] base the radix used in formatting
* @param[out] out the output buffer
* @param[in] out_length the length of the output buffer
* @return whether the formatting was successful or not
*/
bool tostring128_signed(const uint128_t *const number,
uint32_t base,
char *const out,
uint32_t out_length) {
uint128_t max_unsigned_val;
uint128_t max_signed_val;
uint128_t one_val;
uint128_t two_val;
uint128_t tmp;
// showing negative numbers only really makes sense in base 10
if (base == 10) {
explicit_bzero(&one_val, sizeof(one_val));
LOWER(one_val) = 1;
explicit_bzero(&two_val, sizeof(two_val));
LOWER(two_val) = 2;
memset(&max_unsigned_val, 0xFF, sizeof(max_unsigned_val));
divmod128(&max_unsigned_val, &two_val, &max_signed_val, &tmp);
if (gt128(number, &max_signed_val)) // negative value
{
sub128(&max_unsigned_val, number, &tmp);
add128(&tmp, &one_val, &tmp);
out[0] = '-';
return tostring128(&tmp, base, out + 1, out_length - 1);
}
}
return tostring128(number, base, out, out_length); // positive value
}

60
src/uint128.h Normal file
View File

@@ -0,0 +1,60 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
// Adapted from https://github.com/calccrypto/uint256_t
#ifndef _UINT128_H_
#define _UINT128_H_
#include <stdint.h>
#include <stdbool.h>
typedef struct uint128_t {
uint64_t elements[2];
} uint128_t;
void readu128BE(const uint8_t *const buffer, uint128_t *const target);
bool zero128(const uint128_t *const number);
void copy128(uint128_t *const target, const uint128_t *const number);
void clear128(uint128_t *const target);
void shiftl128(const uint128_t *const number, uint32_t value, uint128_t *const target);
void shiftr128(const uint128_t *const number, uint32_t value, uint128_t *const target);
uint32_t bits128(const uint128_t *const number);
bool equal128(const uint128_t *const number1, const uint128_t *const number2);
bool gt128(const uint128_t *const number1, const uint128_t *const number2);
bool gte128(const uint128_t *const number1, const uint128_t *const number2);
void add128(const uint128_t *const number1,
const uint128_t *const number2,
uint128_t *const target);
void sub128(const uint128_t *const number1,
const uint128_t *const number2,
uint128_t *const target);
void or128(const uint128_t *const number1, const uint128_t *const number2, uint128_t *const target);
void mul128(const uint128_t *const number1,
const uint128_t *const number2,
uint128_t *const target);
void divmod128(const uint128_t *const l,
const uint128_t *const r,
uint128_t *const div,
uint128_t *const mod);
bool tostring128(const uint128_t *const number, uint32_t base, char *const out, uint32_t outLength);
bool tostring128_signed(const uint128_t *const number,
uint32_t base,
char *const out,
uint32_t out_length);
#endif // _UINT128_H_

292
src/uint256.c Normal file
View File

@@ -0,0 +1,292 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
// Adapted from https://github.com/calccrypto/uint256_t
#include <stdio.h>
#include <string.h>
#include "uint256.h"
#include "uint_common.h"
#include "ethUstream.h" // INT256_LENGTH
#include "ethUtils.h" // HEXDIGITS
void readu256BE(const uint8_t *const buffer, uint256_t *const target) {
readu128BE(buffer, &UPPER_P(target));
readu128BE(buffer + 16, &LOWER_P(target));
}
bool zero256(const uint256_t *const number) {
return (zero128(&LOWER_P(number)) && zero128(&UPPER_P(number)));
}
void copy256(uint256_t *const target, const uint256_t *const number) {
copy128(&UPPER_P(target), &UPPER_P(number));
copy128(&LOWER_P(target), &LOWER_P(number));
}
void clear256(uint256_t *const target) {
clear128(&UPPER_P(target));
clear128(&LOWER_P(target));
}
void shiftl256(const uint256_t *const number, uint32_t value, uint256_t *const target) {
if (value >= 256) {
clear256(target);
} else if (value == 128) {
copy128(&UPPER_P(target), &LOWER_P(number));
clear128(&LOWER_P(target));
} else if (value == 0) {
copy256(target, number);
} else if (value < 128) {
uint128_t tmp1;
uint128_t tmp2;
uint256_t result;
shiftl128(&UPPER_P(number), value, &tmp1);
shiftr128(&LOWER_P(number), (128 - value), &tmp2);
add128(&tmp1, &tmp2, &UPPER(result));
shiftl128(&LOWER_P(number), value, &LOWER(result));
copy256(target, &result);
} else if ((256 > value) && (value > 128)) {
shiftl128(&LOWER_P(number), (value - 128), &UPPER_P(target));
clear128(&LOWER_P(target));
} else {
clear256(target);
}
}
void shiftr256(const uint256_t *const number, uint32_t value, uint256_t *const target) {
if (value >= 256) {
clear256(target);
} else if (value == 128) {
copy128(&LOWER_P(target), &UPPER_P(number));
clear128(&UPPER_P(target));
} else if (value == 0) {
copy256(target, number);
} else if (value < 128) {
uint128_t tmp1;
uint128_t tmp2;
uint256_t result;
shiftr128(&UPPER_P(number), value, &UPPER(result));
shiftr128(&LOWER_P(number), value, &tmp1);
shiftl128(&UPPER_P(number), (128 - value), &tmp2);
add128(&tmp1, &tmp2, &LOWER(result));
copy256(target, &result);
} else if ((256 > value) && (value > 128)) {
shiftr128(&UPPER_P(number), (value - 128), &LOWER_P(target));
clear128(&UPPER_P(target));
} else {
clear256(target);
}
}
uint32_t bits256(const uint256_t *const number) {
uint32_t result = 0;
if (!zero128(&UPPER_P(number))) {
result = 128;
uint128_t up;
copy128(&up, &UPPER_P(number));
while (!zero128(&up)) {
shiftr128(&up, 1, &up);
result++;
}
} else {
uint128_t low;
copy128(&low, &LOWER_P(number));
while (!zero128(&low)) {
shiftr128(&low, 1, &low);
result++;
}
}
return result;
}
bool equal256(const uint256_t *const number1, const uint256_t *const number2) {
return (equal128(&UPPER_P(number1), &UPPER_P(number2)) &&
equal128(&LOWER_P(number1), &LOWER_P(number2)));
}
bool gt256(const uint256_t *const number1, const uint256_t *const number2) {
if (equal128(&UPPER_P(number1), &UPPER_P(number2))) {
return gt128(&LOWER_P(number1), &LOWER_P(number2));
}
return gt128(&UPPER_P(number1), &UPPER_P(number2));
}
bool gte256(const uint256_t *const number1, const uint256_t *const number2) {
return gt256(number1, number2) || equal256(number1, number2);
}
void add256(const uint256_t *const number1,
const uint256_t *const number2,
uint256_t *const target) {
uint128_t tmp;
add128(&UPPER_P(number1), &UPPER_P(number2), &UPPER_P(target));
add128(&LOWER_P(number1), &LOWER_P(number2), &tmp);
if (gt128(&LOWER_P(number1), &tmp)) {
uint128_t one;
UPPER(one) = 0;
LOWER(one) = 1;
add128(&UPPER_P(target), &one, &UPPER_P(target));
}
add128(&LOWER_P(number1), &LOWER_P(number2), &LOWER_P(target));
}
void sub256(const uint256_t *const number1,
const uint256_t *const number2,
uint256_t *const target) {
uint128_t tmp;
sub128(&UPPER_P(number1), &UPPER_P(number2), &UPPER_P(target));
sub128(&LOWER_P(number1), &LOWER_P(number2), &tmp);
if (gt128(&tmp, &LOWER_P(number1))) {
uint128_t one;
UPPER(one) = 0;
LOWER(one) = 1;
sub128(&UPPER_P(target), &one, &UPPER_P(target));
}
sub128(&LOWER_P(number1), &LOWER_P(number2), &LOWER_P(target));
}
void or256(const uint256_t *const number1,
const uint256_t *const number2,
uint256_t *const target) {
or128(&UPPER_P(number1), &UPPER_P(number2), &UPPER_P(target));
or128(&LOWER_P(number1), &LOWER_P(number2), &LOWER_P(target));
}
void mul256(const uint256_t *const number1,
const uint256_t *const number2,
uint256_t *const target) {
uint8_t num1[INT256_LENGTH], num2[INT256_LENGTH], result[INT256_LENGTH * 2];
memset(&result, 0, sizeof(result));
for (uint8_t i = 0; i < 4; i++) {
write_u64_be(num1 + i * sizeof(uint64_t), number1->elements[i / 2].elements[i % 2]);
write_u64_be(num2 + i * sizeof(uint64_t), number2->elements[i / 2].elements[i % 2]);
}
cx_math_mult(result, num1, num2, sizeof(num1));
for (uint8_t i = 0; i < 4; i++) {
read_u64_be(result + 32 + i * sizeof(uint64_t), &target->elements[i / 2].elements[i % 2]);
}
}
void divmod256(const uint256_t *const l,
const uint256_t *const r,
uint256_t *const retDiv,
uint256_t *const retMod) {
uint256_t copyd, adder, resDiv, resMod;
uint256_t one;
clear256(&one);
UPPER(LOWER(one)) = 0;
LOWER(LOWER(one)) = 1;
uint32_t diffBits = bits256(l) - bits256(r);
clear256(&resDiv);
copy256(&resMod, l);
if (gt256(r, l)) {
copy256(retMod, l);
clear256(retDiv);
} else {
shiftl256(r, diffBits, &copyd);
shiftl256(&one, diffBits, &adder);
if (gt256(&copyd, &resMod)) {
shiftr256(&copyd, 1, &copyd);
shiftr256(&adder, 1, &adder);
}
while (gte256(&resMod, r)) {
if (gte256(&resMod, &copyd)) {
sub256(&resMod, &copyd, &resMod);
or256(&resDiv, &adder, &resDiv);
}
shiftr256(&copyd, 1, &copyd);
shiftr256(&adder, 1, &adder);
}
copy256(retDiv, &resDiv);
copy256(retMod, &resMod);
}
}
bool tostring256(const uint256_t *const number,
uint32_t baseParam,
char *const out,
uint32_t outLength) {
uint256_t rDiv;
uint256_t rMod;
uint256_t base;
copy256(&rDiv, number);
clear256(&rMod);
clear256(&base);
UPPER(LOWER(base)) = 0;
LOWER(LOWER(base)) = baseParam;
uint32_t offset = 0;
if ((outLength == 0) || (baseParam < 2) || (baseParam > 16)) {
return false;
}
do {
divmod256(&rDiv, &base, &rDiv, &rMod);
out[offset++] = HEXDIGITS[(uint8_t) LOWER(LOWER(rMod))];
} while (!zero256(&rDiv) && (offset < outLength));
if (offset == outLength) { // destination buffer too small
if (outLength > 3) {
strlcpy(out, "...", outLength);
} else {
out[0] = '\0';
}
return false;
}
out[offset] = '\0';
reverseString(out, offset);
return true;
}
/**
* Format a uint256_t into a string as a signed integer
*
* @param[in] number the number to format
* @param[in] base the radix used in formatting
* @param[out] out the output buffer
* @param[in] out_length the length of the output buffer
* @return whether the formatting was successful or not
*/
bool tostring256_signed(const uint256_t *const number,
uint32_t base,
char *const out,
uint32_t out_length) {
uint256_t max_unsigned_val;
uint256_t max_signed_val;
uint256_t one_val;
uint256_t two_val;
uint256_t tmp;
// showing negative numbers only really makes sense in base 10
if (base == 10) {
explicit_bzero(&one_val, sizeof(one_val));
LOWER(LOWER(one_val)) = 1;
explicit_bzero(&two_val, sizeof(two_val));
LOWER(LOWER(two_val)) = 2;
memset(&max_unsigned_val, 0xFF, sizeof(max_unsigned_val));
divmod256(&max_unsigned_val, &two_val, &max_signed_val, &tmp);
if (gt256(number, &max_signed_val)) // negative value
{
sub256(&max_unsigned_val, number, &tmp);
add256(&tmp, &one_val, &tmp);
out[0] = '-';
return tostring256(&tmp, base, out + 1, out_length - 1);
}
}
return tostring256(number, base, out, out_length); // positive value
}

61
src/uint256.h Normal file
View File

@@ -0,0 +1,61 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
// Adapted from https://github.com/calccrypto/uint256_t
#ifndef _UINT256_H_
#define _UINT256_H_
#include <stdint.h>
#include <stdbool.h>
#include "uint128.h"
typedef struct uint256_t {
uint128_t elements[2];
} uint256_t;
void readu256BE(const uint8_t *const buffer, uint256_t *const target);
bool zero256(const uint256_t *const number);
void copy256(uint256_t *const target, const uint256_t *const number);
void clear256(uint256_t *const target);
void shiftl256(const uint256_t *const number, uint32_t value, uint256_t *const target);
void shiftr256(const uint256_t *const number, uint32_t value, uint256_t *const target);
uint32_t bits256(const uint256_t *const number);
bool equal256(const uint256_t *const number1, const uint256_t *const number2);
bool gt256(const uint256_t *const number1, const uint256_t *const number2);
bool gte256(const uint256_t *const number1, const uint256_t *const number2);
void add256(const uint256_t *const number1,
const uint256_t *const number2,
uint256_t *const target);
void sub256(const uint256_t *const number1,
const uint256_t *const number2,
uint256_t *const target);
void or256(const uint256_t *const number1, const uint256_t *const number2, uint256_t *const target);
void mul256(const uint256_t *const number1,
const uint256_t *const number2,
uint256_t *const target);
void divmod256(const uint256_t *const l,
const uint256_t *const r,
uint256_t *const div,
uint256_t *const mod);
bool tostring256(const uint256_t *const number, uint32_t base, char *const out, uint32_t outLength);
bool tostring256_signed(const uint256_t *const number,
uint32_t base,
char *const out,
uint32_t out_length);
#endif // _UINT256_H_

60
src/uint_common.c Normal file
View File

@@ -0,0 +1,60 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
// Adapted from https://github.com/calccrypto/uint256_t
#include "uint_common.h"
void write_u64_be(uint8_t *const buffer, uint64_t value) {
buffer[0] = ((value >> 56) & 0xff);
buffer[1] = ((value >> 48) & 0xff);
buffer[2] = ((value >> 40) & 0xff);
buffer[3] = ((value >> 32) & 0xff);
buffer[4] = ((value >> 24) & 0xff);
buffer[5] = ((value >> 16) & 0xff);
buffer[6] = ((value >> 8) & 0xff);
buffer[7] = (value & 0xff);
}
void read_u64_be(const uint8_t *const in, uint64_t *const out) {
uint8_t *out_ptr = (uint8_t *) out;
*out_ptr++ = in[7];
*out_ptr++ = in[6];
*out_ptr++ = in[5];
*out_ptr++ = in[4];
*out_ptr++ = in[3];
*out_ptr++ = in[2];
*out_ptr++ = in[1];
*out_ptr = in[0];
}
uint64_t readUint64BE(const uint8_t *const buffer) {
return (((uint64_t) buffer[0]) << 56) | (((uint64_t) buffer[1]) << 48) |
(((uint64_t) buffer[2]) << 40) | (((uint64_t) buffer[3]) << 32) |
(((uint64_t) buffer[4]) << 24) | (((uint64_t) buffer[5]) << 16) |
(((uint64_t) buffer[6]) << 8) | (((uint64_t) buffer[7]));
}
void reverseString(char *const str, uint32_t length) {
uint32_t i, j;
for (i = 0, j = length - 1; i < j; i++, j--) {
char c;
c = str[i];
str[i] = str[j];
str[j] = c;
}
}

35
src/uint_common.h Normal file
View File

@@ -0,0 +1,35 @@
/*******************************************************************************
* Ledger Ethereum App
* (c) 2016-2019 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
// Adapted from https://github.com/calccrypto/uint256_t
#ifndef _UINT_COMMON_H_
#define _UINT_COMMON_H_
#include <stdint.h>
#define UPPER_P(x) x->elements[0]
#define LOWER_P(x) x->elements[1]
#define UPPER(x) x.elements[0]
#define LOWER(x) x.elements[1]
void write_u64_be(uint8_t *const buffer, uint64_t value);
void read_u64_be(const uint8_t *const in, uint64_t *const out);
uint64_t readUint64BE(const uint8_t *const buffer);
void reverseString(char *const str, uint32_t length);
#endif //_UINT_COMMON_H_