Skip to content

Signed Transfer Manager #533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contracts/datastore/DataStore.sol
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ contract DataStore is DataStoreStorage, IDataStore {
* @param _securityToken address of the security token
*/
function setSecurityToken(address _securityToken) external onlyOwner {
//NB When dataStore is generated, the security token address is automatically set via the constructor in DataStoreProxy.
if(address(securityToken) != address(0)) {
require(msg.sender == IOwnable(address(securityToken)).owner(), "Unauthorized");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ contract KYCTransferManagerFactory is ModuleFactory {
* @notice Type of the Module factory
*/
function getTypes() external view returns(uint8[] memory) {
uint8[] memory res = new uint8[](1);
uint8[] memory res = new uint8[](2);
res[0] = 2;
res[1] = 6;
return res;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
pragma solidity ^0.5.0;

import "../../TransferManager/TransferManager.sol";
import "../../../interfaces/IDataStore.sol";
import "../../../interfaces/ISecurityToken.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";

/**
* @title Transfer Manager module for verifing transations with a signed message
*/
contract SignedTransferManager is TransferManager {
using SafeMath for uint256;

bytes32 constant public ADMIN = "ADMIN";

//Keeps track of if the signature has been used or invalidated
//mapping(bytes => bool) invalidSignatures;
bytes32 constant public INVALID_SIG = "INVALIDSIG";

//keep tracks of the address that allows to sign messages
//mapping(address => bool) public signers;
bytes32 constant public SIGNER = "SIGNER";

// Emit when signer stats was changed
event SignersUpdated(address[] _signers, bool[] _signersStats);

// Emit when a signature has been deemed invalid
event SignatureInvalidated(bytes _data);


/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress)
public
Module(_securityToken, _polyAddress)
{
}

/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() external pure returns (bytes4) {
return bytes4(0);
}

/**
* @notice function to check if a signature is still valid
* @param _data signature
*/
function checkSignatureValidity(bytes calldata _data) external view returns(bool) {
address targetAddress;
uint256 nonce;
uint256 expiry;
bytes memory signature;
(targetAddress, nonce, expiry, signature) = abi.decode(_data, (address, uint256, uint256, bytes));
if (targetAddress != address(this) || expiry < now || signature.length == 0 || _checkSignatureIsInvalid(signature))
return false;
return true;
}

function checkSigner(address _signer) external view returns(bool) {
return _checkSigner(_signer);
}

/**
* @notice function to remove or add signer(s) onto the signer mapping
* @param _signers address array of signers
* @param _signersStats bool array of signers stats
*/
function updateSigners(address[] calldata _signers, bool[] calldata _signersStats) external withPerm(ADMIN) {
require(_signers.length == _signersStats.length, "Array length mismatch");
IDataStore dataStore = IDataStore(ISecurityToken(securityToken).dataStore());
for(uint256 i=0; i<_signers.length; i++) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting to store Signer addresses in the data store. I guess this makes sense, esp. if "signers" are going to be used in other places and would make upgrading the module easier (via a remove and re-add).

require(_signers[i] != address(0), "Invalid address");
dataStore.setBool(keccak256(abi.encodePacked(SIGNER, _signers[i])), _signersStats[i]);
}
emit SignersUpdated(_signers, _signersStats);
}

/**
* @notice allow verify transfer with signature
* @param _from address transfer from
* @param _to address transfer to
* @param _amount transfer amount
* @param _data signature
* @param _isTransfer bool value of isTransfer
* Sig needs to be valid (not used or deemed as invalid)
* Signer needs to be in the signers mapping
*/
function verifyTransfer(address _from, address _to, uint256 _amount, bytes memory _data , bool _isTransfer) public returns(Result) {
if (!paused) {

require (_isTransfer == false || msg.sender == securityToken, "Sender is not ST");

if (_data.length == 0)
return Result.NA;

address targetAddress;
uint256 nonce;
uint256 expiry;
bytes memory signature;
(targetAddress, nonce, expiry, signature) = abi.decode(_data, (address, uint256, uint256, bytes));

if (address(this) != targetAddress || signature.length == 0 || _checkSignatureIsInvalid(signature) || expiry < now)
return Result.NA;

bytes32 hash = keccak256(abi.encodePacked(targetAddress, nonce, expiry, _from, _to, _amount));
bytes32 prependedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Encoder Library could be used

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll refactor a bit to use this (and in other places if needed)

address signer = _recoverSignerAdd(prependedHash, signature);

if (!_checkSigner(signer)) {
return Result.NA;
} else if(_isTransfer) {
_invalidateSignature(signature);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of SignatureInvalidated event, we could emit SignatureUsed or something +ve event as transaction get succeed. For invalidateSignature() function this event makes sense but for a successful transfer, it will create confusion.

return Result.VALID;
} else {
return Result.VALID;
}
}
return Result.NA;
}

/**
* @notice allow signers to deem a signature invalid
* @param _from address transfer from
* @param _to address transfer to
* @param _amount transfer amount
* @param _data signature
* Sig needs to be valid (not used or deemed as invalid)
* Signer needs to be in the signers mapping
*/
function invalidateSignature(address _from, address _to, uint256 _amount, bytes calldata _data) external {
require(_checkSigner(msg.sender), "Unauthorized Signer");

address targetAddress;
uint256 nonce;
uint256 expiry;
bytes memory signature;
(targetAddress, nonce, expiry, signature) = abi.decode(_data, (address, uint256, uint256, bytes));

require(!_checkSignatureIsInvalid(signature), "Signature already invalid");
require(targetAddress == address(this), "Signature not for this module");

bytes32 hash = keccak256(abi.encodePacked(targetAddress, nonce, expiry, _from, _to, _amount));
bytes32 prependedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));

require(_recoverSignerAdd(prependedHash, signature) == msg.sender, "Incorrect Signer");

_invalidateSignature(signature);
}

/**
* @notice used to recover signers' address from signature
*/
function _recoverSignerAdd(bytes32 _hash, bytes memory _data) internal pure returns(address) {

if (_data.length != 65) {
return address(0);
}

bytes32 r;
bytes32 s;
uint8 v;

assembly {
r := mload(add(_data, 32))
s := mload(add(_data, 64))
v := and(mload(add(_data, 65)), 255)
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {

}

return ecrecover(_hash, v, r, s);
}

/**
* @notice Return the permissions flag that are associated with ManualApproval transfer manager
*/
function getPermissions() public view returns(bytes32[] memory) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}

function _checkSignatureIsInvalid(bytes memory _data) internal view returns(bool) {
IDataStore dataStore = IDataStore(ISecurityToken(securityToken).dataStore());
return dataStore.getBool(keccak256(abi.encodePacked(INVALID_SIG, _data)));
}

function _checkSigner(address _signer) internal view returns(bool) {
IDataStore dataStore = IDataStore(ISecurityToken(securityToken).dataStore());
return dataStore.getBool(keccak256(abi.encodePacked(SIGNER, _signer)));
}

function _invalidateSignature(bytes memory _data) internal {
IDataStore dataStore = IDataStore(ISecurityToken(securityToken).dataStore());
dataStore.setBool(keccak256(abi.encodePacked(INVALID_SIG, _data)), true);
emit SignatureInvalidated(_data);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
pragma solidity ^0.5.0;

import "./SignedTransferManager.sol";
import "../../ModuleFactory.sol";

/**
* @title Factory for deploying SignedTransferManager module
*/
contract SignedTransferManagerFactory is ModuleFactory {

/**
* @notice Constructor
*/
constructor (uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public
ModuleFactory(_setupCost, _usageCost, _subscriptionCost)
{
version = "1.0.0";
name = "SignedTransferManager";
title = "Signed Transfer Manager";
description = "Manage transfers using a signature";
compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
}


/**
* @notice used to launch the Module with the help of factory
* @return address Contract address of the Module
*/
// function deploy(bytes calldata /* _data */) external returns(address) {
// if (setupCost > 0)
// require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided");
// address signedTransferManager = new SignedTransferManager(msg.sender, address(polyToken));
// emit GenerateModuleFromFactory(address(signedTransferManager), getName(), address(this), msg.sender, setupCost, now);
// return address(signedTransferManager);
// }

function deploy(bytes calldata /* _data */) external returns(address) {
address polyToken = _takeFee();
SignedTransferManager signedTransferManager = new SignedTransferManager(msg.sender, polyToken);
emit GenerateModuleFromFactory(address(signedTransferManager), getName(), address(this), msg.sender, now);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it follow the proxy approach of deployment ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For "Experimental" modules we haven't been using the Proxy deployment approach.

return address(signedTransferManager);
}


/**
* @notice Type of the Module factory
*/
function getTypes() external view returns(uint8[] memory) {
uint8[] memory res = new uint8[](2);
res[0] = 2;
res[1] = 6;
return res;
}

/**
* @notice Get the name of the Module
*/
function getName() public view returns(bytes32) {
return name;
}

/**
* @notice Get the description of the Module
*/
function getDescription() external view returns(string memory) {
return description;
}

/**
* @notice Get the version of the Module
*/
function getVersion() external view returns(string memory) {
return version;
}

/**
* @notice Get the title of the Module
*/
function getTitle() external view returns(string memory) {
return title;
}

/**
* @notice Get the setup cost of the module
*/
function getSetupCost() external view returns (uint256) {
return setupCost;
}

/**
* @notice Get the Instructions that helped to used the module
*/
function getInstructions() external view returns(string memory) {
return "Allows an issuer to maintain a list of signers who can validate transfer request using signatures. A mapping is used to track valid signers which can be managed by the issuer. verifytransfer function takes in a signature and if the signature is valid, it will verify the transfer. invalidSigature function allow the signer to make a signature invalid after it is signed. Init function takes no parameters.";
}

/**
* @notice Get the tags related to the module factory
*/
function getTags() public view returns(bytes32[] memory) {
bytes32[] memory availableTags = new bytes32[](2);
availableTags[0] = "General";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be "Signed"

availableTags[1] = "Transfer Restriction";
return availableTags;
}


}
1 change: 1 addition & 0 deletions contracts/tokens/STFactory.sol
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ contract STFactory is ISTFactory {
_polymathRegistry
);
newSecurityToken.addModule(transferManagerFactory, "", 0, 0);
//NB When dataStore is generated, the security token address is automatically set via the constructor in DataStoreProxy.
newSecurityToken.changeDataStore(dataStoreFactory.generateDataStore(address(newSecurityToken)));
newSecurityToken.transferOwnership(_issuer);
return address(newSecurityToken);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
"request-promise": "^4.2.2",
"truffle-contract": "^3.0.4",
"truffle-hdwallet-provider-privkey": "0.2.0",
"web3": "1.0.0-beta.34"
"web3": "1.0.0-beta.35"
},
"devDependencies": {
"@soldoc/soldoc": "^0.4.3",
Expand Down
14 changes: 14 additions & 0 deletions test/helpers/createInstances.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const STRGetter = artifacts.require("./STRGetter.sol");
const MockWrongTypeFactory = artifacts.require("./MockWrongTypeFactory.sol");
const DataStoreLogic = artifacts.require('./DataStore.sol');
const DataStoreFactory = artifacts.require('./DataStoreFactory.sol');
const SignedTransferManagerFactory = artifacts.require("./SignedTransferManagerFactory");

const Web3 = require("web3");
let BN = Web3.utils.BN;
Expand Down Expand Up @@ -88,6 +89,7 @@ let I_SecurityTokenRegistryProxy;
let I_STRProxied;
let I_MRProxied;
let I_STRGetter;
let I_SignedTransferManagerFactory;

// Initial fee for ticker registry and security token registry
const initRegFee = new BN(web3.utils.toWei("250"));
Expand Down Expand Up @@ -494,3 +496,15 @@ export async function deployMockWrongTypeRedemptionAndVerifyed(accountPolymath,
await registerAndVerifyByMR(I_MockWrongTypeBurnFactory.address, accountPolymath, MRProxyInstance);
return Promise.all(new Array(I_MockWrongTypeBurnFactory));
}

export async function deploySignedTMAndVerifyed(accountPolymath, MRProxyInstance, polyToken, setupCost) {
I_SignedTransferManagerFactory = await SignedTransferManagerFactory.new(setupCost, 0, 0, { from: accountPolymath });
assert.notEqual(
I_SignedTransferManagerFactory.address.valueOf(),
"0x0000000000000000000000000000000000000000",
"SignedTransferManagerFactory contract was not deployed"
);

await registerAndVerifyByMR(I_SignedTransferManagerFactory.address, accountPolymath, MRProxyInstance);
return new Array(I_SignedTransferManagerFactory);
}
Loading