import random
import os
from solc import compile_files,compile_source,link_code
msg = [""" function BubbleSort_1(uint num) view public returns (uint) {
uint size=8;
for (uint i = 0; i < size -1; i++)
{
for (uint j = size - 1; j > i ; j--)
{
if (a[j-1] > a[j])
{
uint temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
return a[0];
}
""",
""" function BubbleSort_2() view public returns (uint){
uint size=8;
bool bSwaped = true;
for (uint i = 0; i < size -1; i++)
{
bSwaped = false;
for (uint j = size - 1; j > i ; j--)
{
if (a[j-1] > a[j])
{
uint temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
bSwaped = true;
}
}
if (!bSwaped)
break;
}
return a[0];
}
""",
""" function BubbleSort_3() view public returns (uint){
uint size=8;
uint lastSwapPos = 0;
uint lastSwapPosTemp = 0;
for (uint i = 0; i < size - 1; i++)
{
lastSwapPos = lastSwapPosTemp;
for (uint j = size - 1; j >lastSwapPos; j--)
{
if (a[j - 1] > a[j])
{
uint temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
lastSwapPosTemp = j;
}
}
if (lastSwapPos == lastSwapPosTemp)
break;
}
return a[0];
}
"""]
# 遍历目标路径
for i in os.listdir("D:/py代码/未完成"):
# 打开文件读取文件,删除最后一行,关闭文件
dire="D:/py代码/未完成/"+i
file1 = open(dire, "r", encoding="utf-8")
# 记录代码内容的列表
lines = [dire for dire in file1]
# 获取列表长度
length = len(lines)
# 关闭文件
file1.close()
for j in range(length-1):
# 去除内容左空格
lines[j].lstrip()
# 判断是否为contract
if lines[j][:8]=="contract":
# 插入全局变量
lines.insert(j+1, " uint[] a=[7,6,5,4,3,2,1,0];"+'\n')
# 追加冒泡函数
# 随机生成插入函数的个数
num1 = random.randint(1, 2)
if num1 == 1:
num2 = random.randint(0, 2)
lines.insert(j + 2, msg[num2])
break
if num1 == 2:
# 生成第一个随机函数数
num2 = random.randint(0, 2)
lines.insert(j + 2, msg[num2])
# 生成第二个随机函数数
num3 = random.randint(0, 2)
# 如果第二次生成的随机数和第一次不同,就再插入,否则当插入一个函数处理
if num3 != num2:
lines.insert(j + 2, msg[num3])
break
# 打开文件,将lines内容写入
file1 = open(dire, "w", encoding="utf-8")
file1.write("".join(lines))
file1.close()
# 打开文件获取文件内容
file1 = open(dire, "r", encoding="utf-8")
lines = [dire for dire in file1]
file1.close()
# 对文件内容进行编译
context = "".join(lines)
# 编译失败的文件被命名为error
try:
test = compile_source(context)
continue
except Exception as e:
print("error==>", e)
new = "D:/py代码/未完成/"+'er'+i
os.rename(dire, new)
continue
print("Finish!")