当前位置: 首页 > news >正文

Solidity拓展:数学运算过程中数据长度溢出的问题

 

 

在数学运算过程中假如超过了长度则值会变成该类型的最小值,如果小于了该长度则变成最大值

  • 数据上溢
uint8 numA = 255;
numA++;

 uint8的定义域为[0,255],现在numA已经到顶了,numA++会使num变成0(由于256已经超过定义域,它会越过256,变成0),即数据发生上溢(越过上边界,叫上溢)。255 --> 256 -->0 上溢。

  • 数据下溢
uint8 numB = 0;
numB--;

numB本身是低水位线,现在numB-- 会使num变成255(由于-1已经超过定义域,所以它会越过-1,变成255),即数据发生下溢(越过下边界,叫下溢)。0–> -1 --> 255 下溢。  

 可以通过引用 OpenZeppelin的 SafeMath v2.5.x 库,或者自定义一个SafeMath合约,来避免该问题。
    库是 Solidity 中一种特殊的合约,它给原始数据类型增加了一些方法: add(), sub(), mul(), 以及 div()。
    先引用或者import SafeMath库,然后声明 using SafeMath for uint256 ,再通过变量名来调用这些方法。
 

方法1:

导入库import "SafeMath"  

给变量使用库 using SafeMath for 变量类型

传递参数给库中add函数

uint e=255;

e=参数1.add(参数2)           底层是 参数1传给a,参数2传给b 

方法2:

也可以自己创建一个库,用library声明,而不是contract

library SafeMath {

func add(uint8 a,uint b) internal pure returns(uint 8){ 检验加法

       uint8 = a+b;

       assert(c>=a);

       assert()函数可以用来判断参数是否成立,若不成立则弹出一个错误

       return c;}}

试例

import "./safemath.sol";          //1)引用库
using SafeMath for uint256;       //2)声明指定的类型uint256 a = 5;
uint256 b = a.add(3); // 5 + 3 = 8  //3)用变量名来调用方法
uint256 c = a.mul(2); // 5 * 2 = 10

库合约源码

pragma solidity ^0.4.18;/*** @title SafeMath* @dev Math operations with safety checks that throw on error*/
library SafeMath {/*** @dev Multiplies two numbers, throws on overflow.*/function mul(uint256 a, uint256 b) internal pure returns (uint256) {if (a == 0) {return 0;}uint256 c = a * b;assert(c / a == b);return c;}/*** @dev Integer division of two numbers, truncating the quotient.*/function div(uint256 a, uint256 b) internal pure returns (uint256) {// assert(b > 0); // Solidity automatically throws when dividing by 0uint256 c = a / b;// assert(a == b * c + a % b); // There is no case in which this doesn't holdreturn c;}/*** @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).*/function sub(uint256 a, uint256 b) internal pure returns (uint256) {assert(b <= a);return a - b;}/*** @dev Adds two numbers, throws on overflow.*/function add(uint256 a, uint256 b) internal pure returns (uint256) {uint256 c = a + b;assert(c >= a);return c;}
}/*** @title SafeMath32* @dev SafeMath library implemented for uint32*/
library SafeMath32 {function mul(uint32 a, uint32 b) internal pure returns (uint32) {if (a == 0) {return 0;}uint32 c = a * b;assert(c / a == b);return c;}function div(uint32 a, uint32 b) internal pure returns (uint32) {// assert(b > 0); // Solidity automatically throws when dividing by 0uint32 c = a / b;// assert(a == b * c + a % b); // There is no case in which this doesn't holdreturn c;}function sub(uint32 a, uint32 b) internal pure returns (uint32) {assert(b <= a);return a - b;}function add(uint32 a, uint32 b) internal pure returns (uint32) {uint32 c = a + b;assert(c >= a);return c;}
}/*** @title SafeMath16* @dev SafeMath library implemented for uint16*/
library SafeMath16 {function mul(uint16 a, uint16 b) internal pure returns (uint16) {if (a == 0) {return 0;}uint16 c = a * b;assert(c / a == b);return c;}function div(uint16 a, uint16 b) internal pure returns (uint16) {// assert(b > 0); // Solidity automatically throws when dividing by 0uint16 c = a / b;// assert(a == b * c + a % b); // There is no case in which this doesn't holdreturn c;}function sub(uint16 a, uint16 b) internal pure returns (uint16) {assert(b <= a);return a - b;}function add(uint16 a, uint16 b) internal pure returns (uint16) {uint16 c = a + b;assert(c >= a);return c;}
}library SafeMath8 {function mul(uint8 a, uint8 b) internal pure returns (uint8) {if (a == 0) {return 0;}uint8 c = a * b;assert(c / a == b);return c;}function div(uint8 a, uint8 b) internal pure returns (uint8) {// assert(b > 0); // Solidity automatically throws when dividing by 0uint8 c = a / b;// assert(a == b * c + a % b); // There is no case in which this doesn't holdreturn c;}function sub(uint8 a, uint8 b) internal pure returns (uint8) {assert(b <= a);return a - b;}function add(uint8 a, uint8 b) internal pure returns (uint8) {uint8 c = a + b;assert(c >= a);return c;}
}

1.自增修改

简单变量

uint numA;
numA++;

优化后 

import "./safemath.sol";
using SafeMath for uint256;uint numA;
//numA++;
numA = numA.add(1);

map

mapping(address => uint) ownerAppleCount;
ownerAppleCount[msg.sender]++;

优化后 

import "./safemath.sol";
using SafeMath for uint256;mapping(address => uint) ownerAppleCount;
//ownerAppleCount[msg.sender]++;
ownerAppleCount[msg.sender] = ownerAppleCount[msg.sender].add(1);

结构体 

struct Apple {uint32 id;	uint   weight;string color;
}
Apple zhaoApple = Apple(100,150,"red");
zhaoApple.weight++;

优化后 

import "./safemath.sol";
using SafeMath for uint256;
using SafeMath32 for uint32;struct Apple {uint32 id;	uint   weight;string color;
}
Apple zhaoApple = Apple(100,150,"red");
//zhaoApple.weight++;
zhaoApple.weight = zhaoApple.weight.add(1);

2.自减修改

简单变量

uint8 numB;
numB--;

优化后 

import "./safemath.sol";
using SafeMath8 for uint8;uint8 numB;
//numB--;
numB = numB.sub(1);

相关文章:

Solidity拓展:数学运算过程中数据长度溢出的问题

在数学运算过程中假如超过了长度则值会变成该类型的最小值&#xff0c;如果小于了该长度则变成最大值 数据上溢 uint8 numA 255; numA;uint8的定义域为[0,255]&#xff0c;现在numA已经到顶了&#xff0c;numA会使num变成0(由于256已经超过定义域&#xff0c;它会越过256&…...

【C语言】经典题目(一)

【C语言】字符串刷题篇在这里哦&#xff01; 【C语言】字符串—刷题篇 【C】语言经典题目&#xff0c;五个摘录为一篇&#xff0c;将会持续更新啦&#xff01;&#x1f49e; C语言经典题目 三位数水仙花数完数求利润三个数数字排序 三位数 &#x1f4ab;题目 已知有1、2、3、4…...

Linux 设备树文件手动编译的 shell 脚本

前言 前面通过 Makefile 实现手动编译 Linux 设备树 dts 源文件及其 设备树依赖 dtsi、.h 头文件&#xff0c;如何写成一个 shell 脚本&#xff0c;直接编译呢&#xff1f; 其实就是 把 Makefile 重新编写为 shell 脚本即可 编译设备树 shell 脚本 脚本内容如下&#xff1a…...

C++核心编程——初识STL——STL的基本概念和六大组件

文章目录&#x1f4ac; 一.前言二.STL基本概念和组成①容器②算法③迭代器④空间配置器⑤适配器⑥仿函数 三.STL工作机制 一.前言 长久以来&#xff0c;软件界一直希望建立一种可重复利用的东西&#xff0c;以及一种得以制造出“可重复运用的东西”的方法,让程序员的心血不止于…...

5.2图的BFS与DFS遍历

一.BFS遍历 1.图的广度优先遍历代码实现 说明&#xff1a; 1.广度优先遍历&#xff0c;类比树的层次遍历&#xff08;树属于特殊的图&#xff09; 2.对应算法想象图的物理结构存储&#xff1a; 邻接矩阵表示唯一时间复杂度&#xff1a;O(|V|^2); 邻接表不唯一:O(|V|2|E|)&…...

JSP+SQL网上选课系统(源代码+论文+答辩PPT)

随着科学技术的不断提高,计算机科学日渐成熟,其强大的功能已为人们深刻认识,它已进入人类社会的各个领域并发挥着越来越重要的作用。学生选课系统作为一种现代化的教学技术,以越来越受到人民的重视,是一个学校不可缺少的部分, 学生选课系统就是为了管理好选课信息而设计的。学…...

C语言数据结构——树、堆(堆排序)、TOPK问题

&#x1f436;博主主页&#xff1a;ᰔᩚ. 一怀明月ꦿ ❤️‍&#x1f525;专栏系列&#xff1a;线性代数&#xff0c;C初学者入门训练&#xff0c;题解C&#xff0c;C的使用文章&#xff0c;「初学」C&#xff0c;数据结构 &#x1f525;座右铭&#xff1a;“不要等到什么都没…...

springboot+vue 刘老师

课程内容 前端&#xff1a;vue elementui 后端&#xff1a;springboot mybatisplus 公共云部署 ------boot-------- 热部署 不用devtools&#xff0c;交给jrebel工具 RequestMapping ​ 参数 value 路径 method 方法consumes 请求媒体类型 如 application/jsonproduces …...

学生网上考试报名系统的设计与实现

技术栈&#xff1a; MySQL、Maven、SpringBoot、Spring、SpringMVC、MyBatis、HikariCP、fastjson、slf4j系统功能&#xff1a;用户角色&#xff1a; &#xff08;1&#xff09;登录&#xff1a;用户在登录界面输入正确的账户名和密码&#xff0c;点击登录&#xff0c;系统将与…...

Jmeter实现分布式并发

Jmeter实现分布式并发&#xff0c;即使用远程机执行用例。 环境&#xff1a; VMware Fusion Windows系统是win7。 操作过程 1、Master在jmeter.properties添加remote_hosts 2、Slave在jmeter.properties添加server_port 同时把remote_hosts修改为和主机&#xff08;Master…...

动态xml文件配置 hibernate validator 约束校验

父文章 入参校验产品化 schema_个人渣记录仅为自己搜索用的博客-CSDN博客 一般都是通过 注解进行校验, 很少看到 通过配置来进行校验. 自己再通过谷歌找到了官网文档hibernate validator constraint from xml Hibernate Validator 8.0.0.Final - Jakarta Bean Validation Re…...

Vue绑定class样式与style样式

1&#xff0c;回顾HTML的class属性 答&#xff1a;任何一个HTML标签都能够具有class属性&#xff0c;这个属性可能只有一个值&#xff0c;如class"happs"&#xff0c;也有可能存在多个属性值&#xff0c;如class"happs good blue"&#xff0c;js的原生DOM针…...

集权攻击系列:如何利用PAC新特性对抗黄金票据?

黄金票据简介 黄金票据是一种常见的域内权限维持手段&#xff0c;这种攻击主要是利用了Kerberos认证过程中TGT票据由KRBTGT用户的hash加密的特性&#xff0c;在掌握KRBTGT用户密码之后可以通过签发一张高权限用户的TGT票据&#xff0c;再利用这个TGT向KDC获取域内服务的ST来实…...

同程面试(部分)(未完全解析)

一面 Java直接内存有了解吗&#xff1f;为什么Java NIO的效率更高&#xff1f;Netty用到很多NIO&#xff0c;来了一个请求后Netty是怎么分发的&#xff0c;它里面有哪些角色&#xff1f;粘包、拆包怎么解决&#xff1f;为什么建立TCP连接是三次握手&#xff0c;而不是四次&…...

讯飞星火_VS_文心一言

获得讯飞星火认知大模型体验授权&#xff0c;第一时间来测试一下效果&#xff0c;使用申请手机号登录后&#xff0c;需要同意讯飞SparkDesk体验规则&#xff0c;如下图所示&#xff1a; 同意之后就可以进行体验了&#xff0c;界面如下&#xff1a; 讯飞星火效果体验 以下Promp…...

Java的集合

1. HashMap排序题&#xff0c;上机题。 已知一个HashMap<Integer&#xff0c;User>集合&#xff0c; User有name&#xff08;String&#xff09;和age&#xff08;int&#xff09;属性。请写一个方法实现对HashMap 的排序功能&#xff0c;该方法接收 HashMap<Intege…...

addr2line 使用,定位kernel panic 代码位置

在kernel崩溃时&#xff0c;方便定位代码。 需要打开kernel配置CONFIG_DEBUG_INFO。 需要有System.map和vmlinux文件&#xff0c;一般在out目录。 一般panic的时候会有给出panic的指针&#xff0c;如下down_write。 el1_data说明发生异常了&#xff0c;进入和entry.S文件&a…...

OpenAI目前所有模型介绍

目录 概述 GPT-4 (limted beta) GPT-3.5 GPT-3 各类模型介绍 DALLE Beta Whisper Beta Embeddings Moderation Codex (deprecated) 概述 模型描述GPT-4 Limited beta 一组在 GPT-3.5 上改进的模型&#xff0c;可以理解并生成自然语言或代码GPT-3.5一组在 GPT-3 上改…...

【P43】JMeter 吞吐量控制器(Throughput Controller)

文章目录 一、吞吐量控制器&#xff08;Throughput Controller&#xff09;参数说明二、测试计划设计2.1、Total Executions2.2、Percent Executions2.3、Per User 一、吞吐量控制器&#xff08;Throughput Controller&#xff09;参数说明 允许用户控制后代元素的执行的次数。…...

方正书版命令详解

方正书版常用的排版符包括&#xff1a; 空格&#xff1a;表示文字之间的间距&#xff0c;不同字号的文字需要适当调整空格大小。 省略号&#xff1a;用于省略一段文字&#xff0c;通常用三个点表示&#xff08;…&#xff09;。 破折号&#xff1a;用于表示强调或者断句&…...

深入剖析AI大模型:大模型时代的 Prompt 工程全解析

今天聊的内容&#xff0c;我认为是AI开发里面非常重要的内容。它在AI开发里无处不在&#xff0c;当你对 AI 助手说 "用李白的风格写一首关于人工智能的诗"&#xff0c;或者让翻译模型 "将这段合同翻译成商务日语" 时&#xff0c;输入的这句话就是 Prompt。…...

循环冗余码校验CRC码 算法步骤+详细实例计算

通信过程&#xff1a;&#xff08;白话解释&#xff09; 我们将原始待发送的消息称为 M M M&#xff0c;依据发送接收消息双方约定的生成多项式 G ( x ) G(x) G(x)&#xff08;意思就是 G &#xff08; x ) G&#xff08;x) G&#xff08;x) 是已知的&#xff09;&#xff0…...

工程地质软件市场:发展现状、趋势与策略建议

一、引言 在工程建设领域&#xff0c;准确把握地质条件是确保项目顺利推进和安全运营的关键。工程地质软件作为处理、分析、模拟和展示工程地质数据的重要工具&#xff0c;正发挥着日益重要的作用。它凭借强大的数据处理能力、三维建模功能、空间分析工具和可视化展示手段&…...

【Web 进阶篇】优雅的接口设计:统一响应、全局异常处理与参数校验

系列回顾&#xff1a; 在上一篇中&#xff0c;我们成功地为应用集成了数据库&#xff0c;并使用 Spring Data JPA 实现了基本的 CRUD API。我们的应用现在能“记忆”数据了&#xff01;但是&#xff0c;如果你仔细审视那些 API&#xff0c;会发现它们还很“粗糙”&#xff1a;有…...

OpenLayers 分屏对比(地图联动)

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 地图分屏对比在WebGIS开发中是很常见的功能&#xff0c;和卷帘图层不一样的是&#xff0c;分屏对比是在各个地图中添加相同或者不同的图层进行对比查看。…...

网络编程(UDP编程)

思维导图 UDP基础编程&#xff08;单播&#xff09; 1.流程图 服务器&#xff1a;短信的接收方 创建套接字 (socket)-----------------------------------------》有手机指定网络信息-----------------------------------------------》有号码绑定套接字 (bind)--------------…...

STM32---外部32.768K晶振(LSE)无法起振问题

晶振是否起振主要就检查两个1、晶振与MCU是否兼容&#xff1b;2、晶振的负载电容是否匹配 目录 一、判断晶振与MCU是否兼容 二、判断负载电容是否匹配 1. 晶振负载电容&#xff08;CL&#xff09;与匹配电容&#xff08;CL1、CL2&#xff09;的关系 2. 如何选择 CL1 和 CL…...

[USACO23FEB] Bakery S

题目描述 Bessie 开了一家面包店! 在她的面包店里&#xff0c;Bessie 有一个烤箱&#xff0c;可以在 t C t_C tC​ 的时间内生产一块饼干或在 t M t_M tM​ 单位时间内生产一块松糕。 ( 1 ≤ t C , t M ≤ 10 9 ) (1 \le t_C,t_M \le 10^9) (1≤tC​,tM​≤109)。由于空间…...

JDK 17 序列化是怎么回事

如何序列化&#xff1f;其实很简单&#xff0c;就是根据每个类型&#xff0c;用工厂类调用。逐个完成。 没什么漂亮的代码&#xff0c;只有有效、稳定的代码。 代码中调用toJson toJson 代码 mapper.writeValueAsString ObjectMapper DefaultSerializerProvider 一堆实…...

高分辨率图像合成归一化流扩展

大家读完觉得有帮助记得关注和点赞&#xff01;&#xff01;&#xff01; 1 摘要 我们提出了STARFlow&#xff0c;一种基于归一化流的可扩展生成模型&#xff0c;它在高分辨率图像合成方面取得了强大的性能。STARFlow的主要构建块是Transformer自回归流&#xff08;TARFlow&am…...