forked from ethereum/solc-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinker.js
79 lines (68 loc) · 2.42 KB
/
linker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
var linkBytecode = function (bytecode, libraries) {
// NOTE: for backwards compatibility support old compiler which didn't use file names
var librariesComplete = {};
for (var libraryName in libraries) {
if (typeof libraryName === 'object') {
// API compatible with the standard JSON i/o
for (var lib in libraries[libraryName]) {
librariesComplete[lib] = libraries[libraryName][lib];
librariesComplete[libraryName + ':' + lib] = libraries[libraryName][lib];
}
} else {
// backwards compatible API for early solc-js verisons
var parsed = libraryName.match(/^([^:]*):?(.*)$/);
if (parsed) {
librariesComplete[parsed[2]] = libraries[libraryName];
}
librariesComplete[libraryName] = libraries[libraryName];
}
}
for (libraryName in librariesComplete) {
// truncate to 37 characters
var internalName = libraryName.slice(0, 36);
// prefix and suffix with __
var libLabel = '__' + internalName + Array(37 - internalName.length).join('_') + '__';
var hexAddress = librariesComplete[libraryName];
if (hexAddress.slice(0, 2) !== '0x' || hexAddress.length > 42) {
throw new Error('Invalid address specified for ' + libraryName);
}
// remove 0x prefix
hexAddress = hexAddress.slice(2);
hexAddress = Array(40 - hexAddress.length + 1).join('0') + hexAddress;
while (bytecode.indexOf(libLabel) >= 0) {
bytecode = bytecode.replace(libLabel, hexAddress);
}
}
return bytecode;
};
var findLinkReferences = function (bytecode) {
// find 40 bytes in the pattern of __...<36 digits>...__
// e.g. __Lib.sol:L_____________________________
var linkReferences = {};
var offset = 0;
while (true) {
var found = bytecode.match(/__(.{36})__/);
if (!found) {
break;
}
var start = found.index;
// trim trailing underscores
// NOTE: this has no way of knowing if the trailing underscore was part of the name
var libraryName = found[1].replace(/_+$/gm, '');
if (!linkReferences[libraryName]) {
linkReferences[libraryName] = [];
}
linkReferences[libraryName].push({
// offsets are in bytes in binary representation (and not hex)
start: (offset + start) / 2,
length: 20
});
offset += start + 20;
bytecode = bytecode.slice(start + 20);
}
return linkReferences;
};
module.exports = {
linkBytecode: linkBytecode,
findLinkReferences: findLinkReferences
};