/******************************************************************************* * (c) 2022 Zondax AG * * 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. ********************************************************************************/ // // THIS CODE WAS SECURITY REVIEWED BY KUDELSKI SECURITY, BUT NOT FORMALLY AUDITED // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.17; import "../types/CommonTypes.sol"; /// @title This library is a set of functions meant to handle CBOR serialization and deserialization for BigInt type /// @author Zondax AG library BigIntCBOR { /// @notice serialize BigInt instance to bytes /// @param num BigInt instance to serialize /// @return serialized BigInt as bytes function serializeBigInt(CommonTypes.BigInt memory num) internal pure returns (bytes memory) { bytes memory raw = new bytes(num.val.length + 1); raw[0] = num.neg == true ? bytes1(0x01) : bytes1(0x00); uint index = 1; for (uint i = 0; i < num.val.length; i++) { raw[index] = num.val[i]; index++; } return raw; } /// @notice deserialize big int (encoded as bytes) to BigInt instance /// @param raw as bytes to parse /// @return parsed BigInt instance function deserializeBigInt(bytes memory raw) internal pure returns (CommonTypes.BigInt memory) { if (raw.length == 0) { return CommonTypes.BigInt(hex"00", false); } bytes memory val = new bytes(raw.length - 1); bool neg = false; if (raw[0] == 0x01) { neg = true; } for (uint i = 1; i < raw.length; i++) { val[i - 1] = raw[i]; } return CommonTypes.BigInt(val, neg); } }