Skip to content
This repository was archived by the owner on Apr 12, 2021. It is now read-only.

Commit 96baeba

Browse files
authored
Fix RLPWriter Memory Allocation (#84)
* add failing test case with this issue * add _malloc which works * malloc words not bytes
1 parent 974f76d commit 96baeba

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

contracts/optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol

+19
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ library Lib_RLPWriter {
8989
bytes memory _out
9090
)
9191
{
92+
_malloc(0x20);
9293
bytes memory inputBytes;
9394
assembly {
9495
let m := mload(0x40)
@@ -308,4 +309,22 @@ library Lib_RLPWriter {
308309

309310
return flattened;
310311
}
312+
313+
/**
314+
* Clears memory wherever the free memory is pointing.
315+
* @param _numBytes Number of bytes to clear out (will be rounded up to nearest word).
316+
*/
317+
function _malloc(
318+
uint _numBytes
319+
)
320+
private
321+
pure
322+
{
323+
assembly {
324+
let free_mem := mload(0x40)
325+
for { let offset := 0x00 } lt(offset, _numBytes) { offset := add(offset, 0x20) } {
326+
mstore(add(free_mem, offset), 0x00)
327+
}
328+
}
329+
}
311330
}

contracts/test-libraries/rlp/TestLib_RLPWriter.sol

+13
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pragma experimental ABIEncoderV2;
44

55
/* Library Imports */
66
import { Lib_RLPWriter } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol";
7+
import { TestERC20 } from "../../test-helpers/TestERC20.sol";
78

89
/**
910
* @title TestLib_RLPWriter
@@ -93,4 +94,16 @@ contract TestLib_RLPWriter {
9394
{
9495
return Lib_RLPWriter.writeBool(_in);
9596
}
97+
98+
function writeAddressWithOtherMemory(
99+
address _in
100+
)
101+
public
102+
returns (
103+
bytes memory _out
104+
)
105+
{
106+
new TestERC20();
107+
return Lib_RLPWriter.writeAddress(_in);
108+
}
96109
}

test/contracts/libraries/rlp/Lib_RLPWriter.spec.ts

+9
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,13 @@ describe('Lib_RLPWriter', () => {
4141
})
4242
}
4343
})
44+
45+
describe.only('Use of library with other memory-modifying operations', () => {
46+
it('should allow creation of a contract beforehand and still work', async () => {
47+
const randomAddress = '0x1234123412341234123412341234123412341234'
48+
const rlpEncodedRandomAddress = '0x941234123412341234123412341234123412341234'
49+
const encoded = await Lib_RLPWriter.callStatic.writeAddressWithOtherMemory(randomAddress)
50+
expect(encoded).to.eq(rlpEncodedRandomAddress)
51+
})
52+
})
4453
})

0 commit comments

Comments
 (0)